forked from dotnet/project-system
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDebuggerTraceListener.cs
65 lines (54 loc) · 2.24 KB
/
DebuggerTraceListener.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information.
#if DEBUG
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Reflection;
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem.VS;
using Microsoft.VisualStudio.Shell;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.Packaging
{
[Export(typeof(IPackageService))]
internal sealed class DebuggerTraceListener : TraceListener, IPackageService
{
public Task InitializeAsync(IAsyncServiceProvider asyncServiceProvider)
{
// There's no public API registering a trace listener for a
// non-public trace source, so we need to use reflection
string assemblyName = typeof(AppliesToAttribute).Assembly.FullName;
string typeName = $"Microsoft.VisualStudio.ProjectSystem.TraceUtilities, {assemblyName}";
var type = Type.GetType(typeName);
if (type is null)
{
Assumes.Fail($"Could not find type '{typeName}'");
}
const string sourcePropertyName = "Source";
PropertyInfo? property = type.GetProperty(sourcePropertyName, BindingFlags.NonPublic | BindingFlags.Static);
if (property is null)
{
Assumes.Fail($"Could not find property '{sourcePropertyName}' in type '{typeName}'");
}
var source = (TraceSource)property.GetValue(null);
source.Switch.Level = SourceLevels.Warning;
source.Listeners.Add(this);
return Task.CompletedTask;
}
public override void Write(string message)
{
if (System.Diagnostics.Debugger.IsLogging())
{
System.Diagnostics.Debugger.Log(0, null, message);
}
}
public override void WriteLine(string message)
{
if (System.Diagnostics.Debugger.IsLogging())
{
System.Diagnostics.Debugger.Log(0, null, message + Environment.NewLine);
}
}
}
}
#endif