Skip to content

Commit 3d12417

Browse files
Create ActivityLogLoggerProvider that logs warnings and errors
1 parent ccdb2ee commit 3d12417

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the MIT license. See License.txt in the project root for license information.
3+
4+
using System;
5+
using Microsoft.AspNetCore.Razor.PooledObjects;
6+
using Microsoft.CodeAnalysis.Razor.Logging;
7+
using Microsoft.VisualStudio.Razor.Logging;
8+
9+
namespace Microsoft.VisualStudio.LanguageServices.Razor.Logging;
10+
11+
internal sealed partial class ActivityLogLoggerProvider
12+
{
13+
private sealed class Logger(ActivityLog activityLog, string categoryName) : ILogger
14+
{
15+
private readonly ActivityLog _activityLog = activityLog;
16+
private readonly string _categoryName = categoryName;
17+
18+
public bool IsEnabled(LogLevel logLevel)
19+
=> logLevel is LogLevel.Warning or LogLevel.Error or LogLevel.Critical;
20+
21+
public void Log(LogLevel logLevel, string message, Exception? exception)
22+
{
23+
switch (logLevel)
24+
{
25+
case LogLevel.Error or LogLevel.Critical:
26+
_activityLog.LogError(GetLogMessage(message, exception));
27+
break;
28+
29+
case LogLevel.Warning:
30+
_activityLog.LogWarning(GetLogMessage(message, exception));
31+
break;
32+
}
33+
34+
string GetLogMessage(string message, Exception? exception)
35+
{
36+
using var _ = StringBuilderPool.GetPooledObject(out var builder);
37+
builder.Append($"{DateTime.Now:h:mm:ss.fff} [{_categoryName}] {message}");
38+
39+
if (exception is not null)
40+
{
41+
builder.AppendLine();
42+
builder.Append(exception);
43+
}
44+
45+
return builder.ToString();
46+
}
47+
}
48+
}
49+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the MIT license. See License.txt in the project root for license information.
3+
4+
using System.ComponentModel.Composition;
5+
using Microsoft.CodeAnalysis.Razor.Logging;
6+
using Microsoft.VisualStudio.Razor.Logging;
7+
8+
namespace Microsoft.VisualStudio.LanguageServices.Razor.Logging;
9+
10+
/// <summary>
11+
/// An <see cref="ILoggerProvider"/> that logs any warnings or errors to the Visual Studio Activity Log.
12+
/// </summary>
13+
[Export(typeof(ILoggerProvider))]
14+
[method: ImportingConstructor]
15+
internal sealed partial class ActivityLogLoggerProvider(ActivityLog activityLog) : ILoggerProvider
16+
{
17+
private readonly ActivityLog _activityLog = activityLog;
18+
19+
public ILogger CreateLogger(string categoryName)
20+
=> new Logger(_activityLog, categoryName);
21+
}

0 commit comments

Comments
 (0)