1. Trace the basic use of logs
// Trace log
public static class CoreLog
{
public static void Run()
{
using var fileStream = File.OpenWrite("log.txt");
// Publish subscribe mode
var source = new TraceSource("Trace", SourceLevels.Warning);/ / track the source
source.Listeners.Add(new ConsoleTraceListener());// Listen for output to the console
source.Listeners.Add(new TextWriterTraceListener(fileStream));// Listen output to file, have buffer mechanism
var eventTypes = (TraceEventType[])Enum.GetValues(typeof(TraceEventType));// Trace the event type
var eventId = 1;
foreach (var traceEventType in eventTypes)
{
source.TraceEvent(traceEventType, eventId++,$" This is one{traceEventType}The message");
source.Flush();// Clear buffer}}}Copy the code
2. Format trace logs and export them to a CSV file
public static class Sample05
{
public static void Run()
{
const string filename = "log1.csv";
File.AppendAllText(filename,$"SourceName,EventType,EventId,Message,N/A,ProcessId,N/A,ThreadId,DateTime,{Environment.NewLine}" );
using var fileStream = new FileStream(filename,FileMode.Append);
var listener = new DelimitedListTraceListener(fileStream)
{
Delimiter = ",",
TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.ThreadId
};
var source = new TraceSource("AppTrace", SourceLevels.All);
source.Listeners.Add(new ConsoleTraceListener());
source.Listeners.Add(listener);
source.TraceEvent(TraceEventType.Information,1.$" This is one{TraceEventType.Information}The message"); source.Flush(); }}Copy the code
3. Diagnosis logs
// Diagnostic log
public static class Sample06
{
public class Observer<T> : IObserver<T>
{
private readonly Action<T> _onNext;
public Observer(Action<T> onNext)
{
_onNext = onNext;
}
public void OnCompleted(){}public void OnError(Exception error){}public void OnNext(T value)
{
_onNext(value); }}public static void Run()
{
DiagnosticListener.AllListeners.Subscribe(new Observer<DiagnosticListener>(listener =>
{
if (listener.Name == "AppLog")
{
listener.Subscribe(new Observer<KeyValuePair<string.dynamic>>(eventData =>
{
var (key, value) = eventData;
Console.WriteLine($"Name:{key}");
Console.WriteLine($"Value:{value}"); })); }}));var source = new DiagnosticListener("AppLog");
source.Write("Hello".new
{
Type = 1,
Msg = "11 May 2020"}); }}Copy the code
The installation package
Microsoft.Extensions.DiagnosticAdapter
Copy the code
Use the following
public static class Sample08
{
public class Observer<T> : IObserver<T>
{
private readonly Action<T> _onNext;
public Observer(Action<T> onNext)
{
_onNext = onNext;
}
public void OnCompleted(){}public void OnError(Exception error){}public void OnNext(T value)
{
_onNext(value); }}public class CustomSourceCollector{[DiagnosticName("Hello")]
public void OnHello(int type, string msg)
{
Console.WriteLine($"Type:{type}");
Console.WriteLine($"Msg:{msg}"); }}public static void Run()
{
DiagnosticListener.AllListeners.Subscribe(new Observer<DiagnosticListener>(listener =>
{
if (listener.Name == "AppLog")
{
listener.SubscribeWithAdapter(newCustomSourceCollector()); }}));var source = new DiagnosticListener("AppLog");
source.Write("Hello".new
{
Type = 1,
Msg = "11 May 2020"}); }}Copy the code
4. Use of ILogger and ILoggerFactory
public class Sample01
{
public static void Run()
{
var serviceProvider = new ServiceCollection()
.AddLogging(builder => builder
.AddConsole()
.AddDebug())
.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Sample01>>();//ILoggerFactory
// .CreateLogger("ConsoleApp2.Sample01");
var leveles = (LogLevel[])Enum.GetValues(typeof(LogLevel));
var eventId = 1;
foreach (var level in leveles)
{
logger.Log(level, eventId++,$" This is one{level}The message"); } Console.Read(); }}Copy the code
5. The use of AddTraceSource
public class Sample02
{
public static void Run()
{
var serviceProvider = new ServiceCollection()
.AddLogging(builder =>
{
builder.AddTraceSource(
new SourceSwitch("Sample02".nameof(SourceLevels.All)),/ / release
new DefaultTraceListener {LogFileName = "trace.log"});/ / consumption
builder.AddConsole();
builder.SetMinimumLevel(LogLevel.Trace);
})
.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Sample02>>();
var leveles = (LogLevel[])Enum.GetValues(typeof(LogLevel));
var eventId = 1;
foreach (var level in leveles)
{
logger.Log(level, eventId++,$" This is one{level}The message"); } Console.Read(); }}Copy the code
5.Filter Indicates the use of the log Filter
public class Sample03
{
public static void Run()
{
var serviceProvider = new ServiceCollection()
.AddLogging(builder => builder
.AddFilter((category, level) =>
{
return category switch
{
"LoggerA" => level >= LogLevel.Debug,
"LoggerB" => level >= LogLevel.Warning,
"LoggerC" => level >= LogLevel.None,
_ => level >= LogLevel.Information
};
})
.AddConsole()
.AddDebug())
.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
var loggerA = loggerFactory.CreateLogger("LoggerA");
var loggerB = loggerFactory.CreateLogger("LoggerB");
var loggerC = loggerFactory.CreateLogger("LoggerC");
var leveles = (LogLevel[])Enum.GetValues(typeof(LogLevel));
var eventId = 1;
foreach (var level in leveles)
{
eventId++;
loggerA.Log(level, eventId,$" This is one{level}The message");
loggerB.Log(level, eventId,$" This is one{level}The message");
loggerC.Log(level, eventId,$" This is one{level}The message"); } Console.Read(); }}Copy the code
public class Sample04
{
public static void Run()
{
var serviceProvider = new ServiceCollection()
.AddLogging(builder => builder
.AddFilter((provider, category, level) =>
{
if (provider == typeof(ConsoleLoggerProvider).FullName)
{
return level >= LogLevel.Debug;
}
if (provider == typeof(DebugLoggerProvider).FullName)
{
return level >= LogLevel.Warning;
}
return level >= LogLevel.Information;
})
.AddConsole()
.AddDebug())
.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Sample04>>();
var leveles = (LogLevel[])Enum.GetValues(typeof(LogLevel));
var eventId = 1;
foreach (var level in leveles)
{
logger.Log(level, eventId++,$" This is one{level}The message"); } Console.Read(); }}Copy the code
6. Configure the use of file filters
public class Sample05
{
public static void Run()
{
var config = new ConfigurationBuilder()
.AddJsonFile("log.json")
.Build();
var serviceProvider = new ServiceCollection()
.AddLogging(builder => builder
.AddConfiguration(config)
.AddConsole()
.AddDebug())
.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
var loggerA = loggerFactory.CreateLogger("LoggerA");
var loggerB = loggerFactory.CreateLogger("LoggerB");
var loggerC = loggerFactory.CreateLogger("LoggerC");
var leveles = (LogLevel[])Enum.GetValues(typeof(LogLevel));
var eventId = 1;
foreach (var level in leveles)
{
eventId++;
loggerA.Log(level, eventId,$" This is one{level}The message");
loggerB.Log(level, eventId,$" This is one{level}The message");
loggerC.Log(level, eventId,$" This is one{level}The message"); } Console.Read(); }}Copy the code
7. Log injection
public class Sample06
{
public static void Run()
{
var serviceProvider = new ServiceCollection()
.AddLogging(builder => builder
.SetMinimumLevel(LogLevel.Information)
.AddConsole())
.AddSingleton<GodLog>()
.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<GodLog>();
logger.Log("Hello");
Console.Read();
}
public class GodLog
{
private const string Template = [{LogTime}] records from {Id}-{Name} :{Context}";
private static Action<ILogger, DateTime, int ,string.string, Exception> _logAction;
private readonly ILogger _logger;
public GodLog(ILogger<Sample06> logger)
{
_logger = logger;
_logAction = LoggerMessage.Define<DateTime, int.string.string>(LogLevel.Information, 1, Template);
}
public void Log(string context)
{
_logAction(_logger, DateTime.Now, 1."God", context, null); }}}Copy the code
7.ASP.NET CORE uses logging context
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureLogging(builder =>
builder.AddConsole(options => options.IncludeScopes = true));
webBuilder.UseStartup<Startup>();
});
}
Copy the code
create
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
app.Use(async (context, next) =>
{
using (logger.BeginScope($"Request Trans {Guid.NewGuid()}"))
{
logger.Log(LogLevel.Information,$"Request Begin at {DateTime.Now}");
await next();
logger.Log(LogLevel.Information, $"Request End at {DateTime.Now}"); }}); app.Run(async context =>
{
await Task.Delay(1000);
await context.Response.WriteAsync("Hello");
});
}
Copy the code
Create scope
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
var scopeFactory = LoggerMessage.DefineScope<Guid>("Request Trans {Guid}");
var requestLog = LoggerMessage.Define<string, DateTime>(LogLevel.Information, 0."Request {state} at {DateTime.Now}");
app.Use(async (context, next) =>
{
using (scopeFactory(logger, Guid.NewGuid()))
{
requestLog(logger, "Begin", DateTime.Now, null);
await next();
requestLog(logger, "End", DateTime.Now, null); }}); app.Run(async context =>
{
await Task.Delay(1000);
await context.Response.WriteAsync("Hello");
});
}
Copy the code