诊断日志

master
bicijinlian 2 years ago
parent ac31f0407c
commit 5ddca9ac12

@ -0,0 +1,22 @@
using Microsoft.Extensions.DiagnosticAdapter;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogStudy.DiagnosticLog
{
public class DiagnosticSourceCollector
{
[DiagnosticName("CommandExcute")]
public void OnCommandExcute(string commandType, string commandText)
{
Console.WriteLine($"Event Name: OnCommandExcute");
Console.WriteLine($"CommandType:{commandType}");
Console.WriteLine($"CommandText:{commandText}");
}
}
}

@ -7,4 +7,8 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.1.31" />
</ItemGroup>
</Project> </Project>

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogStudy.DiagnosticLog
{
/// <summary>
/// 观察者
/// </summary>
/// <typeparam name="T"></typeparam>
public class Observer<T> : IObserver<T>
{
private readonly Action<T> _onNext;
public Observer(Action<T> onNext)
{
_onNext = onNext;
}
public void OnCompleted()
{
Console.WriteLine("完成");
}
public void OnError(Exception error)
{
Console.WriteLine($"出现异常:{error.Message}");
}
public void OnNext(T value)
{
_onNext(value);
}
}
}

@ -1 +1,72 @@
Console.WriteLine("Hello, World!"); using System.Diagnostics;
namespace LogStudy.DiagnosticLog
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("======== 诊断日志学习 ========");
DemoA();
DemoB();
}
static void DemoA()
{
var sourceName = "LogStudy-DiagnosticLog-DiagnosticSource";
DiagnosticListener.AllListeners.Subscribe(new Observer<DiagnosticListener>(listener =>
{
if (listener.Name == sourceName)
{
listener.Subscribe(new Observer<KeyValuePair<string, object?>>(eventData =>
{
Console.WriteLine($"Event Name: {eventData.Key}");
if (eventData.Value != null)
{
dynamic payload = eventData.Value;
Console.WriteLine($"CommandType:{payload.CommandType}");
Console.WriteLine($"CommandText:{payload.CommandText}");
}
}));
}
}));
var diagnosticSource = new DiagnosticListener(sourceName);
if (diagnosticSource.IsEnabled())
{
diagnosticSource.Write("CommandExecution", new
{
CommandType = "SQL Server",
CommandText = "select * from tableA",
});
}
}
static void DemoB()
{
var sourceName = "LogStudy-DiagnosticLog-DiagnosticSource2";
DiagnosticListener.AllListeners.Subscribe(new Observer<DiagnosticListener>(listener =>
{
if (listener.Name == sourceName)
{
listener.SubscribeWithAdapter(new DiagnosticSourceCollector());
}
}));
var diagnosticSource = new DiagnosticListener(sourceName);
if (diagnosticSource.IsEnabled())
{
diagnosticSource.Write("CommandExcute", new
{
CommandType = "SQL Server",
CommandText = "update tableA set id=2",
});
}
}
}
}

Loading…
Cancel
Save