Skip to content

Commit

Permalink
事件监听器EventListener使用研究,能够拦截框架内部动作,例如http请求等,不同版本框架的事件没有统一
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Nov 15, 2020
1 parent 9c8b5c5 commit 09e435c
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 6 deletions.
95 changes: 95 additions & 0 deletions NewLife.Core/Log/LogEventListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#if !NET4
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;

namespace NewLife.Log
{
/// <summary>日志事件监听器。用于监听内置事件并写入日志</summary>
public class LogEventListener : EventListener
{
private readonly HashSet<String> _hash = new HashSet<String>();
private readonly HashSet<String> _hash2 = new HashSet<String>();

/// <summary>实例化</summary>
/// <param name="sources"></param>
public LogEventListener(String[] sources)
{
foreach (var item in sources)
{
_hash.Add(item);
}
}

/// <summary>创建事件源。此时决定要不要跟踪</summary>
/// <param name="eventSource"></param>
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (_hash.Contains(eventSource.Name))
{
var log = XTrace.Log;

var level = log.Level switch
{
LogLevel.All => EventLevel.LogAlways,
LogLevel.Debug => EventLevel.Verbose,
LogLevel.Info => EventLevel.Informational,
LogLevel.Warn => EventLevel.Warning,
LogLevel.Error => EventLevel.Error,
LogLevel.Fatal => EventLevel.Critical,
LogLevel.Off => throw new NotImplementedException(),
_ => EventLevel.Informational,
};

EnableEvents(eventSource, level);
}
else if (!_hash2.Contains(eventSource.Name))
{
_hash2.Add(eventSource.Name);

XTrace.WriteLine($"Source={eventSource.Name}");
}
}

/// <summary>写入事件。监听器拦截,并写入日志</summary>
/// <param name="eventData"></param>
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
var log = XTrace.Log;

var level = eventData.Level switch
{
EventLevel.Informational => LogLevel.Info,
EventLevel.LogAlways => LogLevel.All,
EventLevel.Critical => LogLevel.Fatal,
EventLevel.Error => LogLevel.Error,
EventLevel.Warning => LogLevel.Warn,
EventLevel.Verbose => LogLevel.Debug,
_ => LogLevel.Info,
};

#if NET45
XTrace.WriteLine($"#{eventData.EventSource?.Name} ID = {eventData.EventId}");
for (var i = 0; i < eventData.Payload.Count; i++)
{
XTrace.WriteLine($"\tPayload = \"{eventData.Payload[i]}\"");
}
#elif NET50
XTrace.WriteLine($"#{eventData.EventSource?.Name} ThreadID = {eventData.OSThreadId} ID = {eventData.EventId} Name = {eventData.EventName}");
for (var i = 0; i < eventData.Payload.Count; i++)
{
XTrace.WriteLine($"\tName = \"{eventData.PayloadNames[i]}\" Value = \"{eventData.Payload[i]}\"");
}
#else
XTrace.WriteLine($"#{eventData.EventSource?.Name} ID = {eventData.EventId} Name = {eventData.EventName}");
for (var i = 0; i < eventData.Payload.Count; i++)
{
XTrace.WriteLine($"\tName = \"{eventData.PayloadNames[i]}\" Value = \"{eventData.Payload[i]}\"");
}
#endif

if (!eventData.Message.IsNullOrEmpty()) log.Write(level, eventData.Message);
}
}
}
#endif
19 changes: 17 additions & 2 deletions Test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,21 @@ private static void Main(String[] args)
set.Debug = true;
set.LogLevel = LogLevel.All;

new LogEventListener(new[] {
"System.Runtime",
"System.Diagnostics.Eventing.FrameworkEventSource",
"System.Transactions.TransactionsEventSource",
"Microsoft-Windows-DotNETRuntime",
//"Private.InternalDiagnostics.System.Net.Sockets",
"System.Net.NameResolution",
//"Private.InternalDiagnostics.System.Net.NameResolution",
"System.Net.Sockets",
//"Private.InternalDiagnostics.System.Net.Http",
"System.Net.Http",
//"System.Data.DataCommonEventSource",
//"Microsoft-Diagnostics-DiagnosticSource",
});

var set2 = XCode.Setting.Current;
set2.Debug = true;
#endif
Expand All @@ -54,7 +69,7 @@ private static void Main(String[] args)
try
{
#endif
Test7();
Test5();
#if !DEBUG
}
catch (Exception ex)
Expand Down Expand Up @@ -154,7 +169,7 @@ private static void Test2()

private static void Test3()
{
var tracer = DefaultTracer.Instance;
var tracer = DefaultTracer.Instance ?? new DefaultTracer();
tracer.MaxSamples = 100;
tracer.MaxErrors = 100;

Expand Down
8 changes: 4 additions & 4 deletions Test/Test.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="Current">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net45;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks>net45;netcoreapp3.1;net5.0</TargetFrameworks>
<OutputPath>..\..\Test\</OutputPath>
<LangVersion>latest</LangVersion>
<Version>1.0.0.1130</Version>
Expand All @@ -27,9 +27,9 @@
<PropertyGroup Condition="'$(TargetFramework)'=='net40'">
<DefineConstants>$(DefineConstants);__WIN__;NET4</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Data.SQLite" Version="1.0.113.6" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net5.0'">
<DefineConstants>$(DefineConstants);__CORE__;NET50</DefineConstants>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\NewLife.Core\NewLife.Core.csproj" />
<ProjectReference Include="..\XCode\XCode.csproj" />
Expand Down

0 comments on commit 09e435c

Please sign in to comment.