using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.DependencyInjection;
|
using Serilog.Events;
|
using Serilog;
|
using System;
|
using System.Collections.Generic;
|
using System.Text;
|
using Serilog.Sinks.SystemConsole.Themes;
|
using Serilog.Filters;
|
|
namespace Utility
|
{
|
public static class ServiceCollectionExtensions
|
{
|
const string template = "时间: {Timestamp:yyyy-MM-dd HH:mm:ss}{NewLine}来源: {SourceContext}{NewLine}内容: [{Level:u3}] {Message}{NewLine}{Exception}{NewLine}";
|
/// <summary>
|
/// 添加配置Serilog
|
/// </summary>
|
/// <param name="services"></param>
|
/// <param name="configuration"></param>
|
/// <returns></returns>
|
public static IServiceCollection AddConfigSerilog(this IServiceCollection services)
|
{
|
// 创建Serilog记录日志
|
Log.Logger = new LoggerConfiguration()
|
.MinimumLevel.Information()
|
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 排除Dotnet自带的日志
|
//.MinimumLevel.Verbose()
|
//.MinimumLevel.Override("System", LogEventLevel.Debug)
|
//.MinimumLevel.Override("Microsoft", LogEventLevel.Debug)
|
//.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Error)
|
//.MinimumLevel.Override("Microsoft.AspNetCore.Cors.Infrastructure.CorsService", LogEventLevel.Error)
|
//.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Error)
|
//.MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Error)
|
// 全部日志写入到Console
|
.WriteTo.Console()
|
.WriteTo.Async(c => c.Console(
|
theme: AnsiConsoleTheme.Literate,
|
outputTemplate: template))
|
// Information日志写入到文件
|
.WriteTo.Async(c => c.File(
|
path: "Logs/Information_.txt",
|
rollingInterval: RollingInterval.Day,
|
fileSizeLimitBytes: 1024 * 1024 * 10,
|
retainedFileCountLimit: 100,
|
outputTemplate: template,
|
restrictedToMinimumLevel: LogEventLevel.Information))
|
// Debug日志写入到文件
|
.WriteTo.Async(c => c.File(
|
path: "Logs/Verbose.txt",
|
rollingInterval: RollingInterval.Day,
|
fileSizeLimitBytes: 1024 * 1024 * 10,
|
retainedFileCountLimit: 100,
|
outputTemplate: template,
|
restrictedToMinimumLevel: LogEventLevel.Verbose))
|
// Warning日志写入到文件
|
.WriteTo.Async(c => c.File(
|
path: "Logs/Warning_.txt",
|
rollingInterval: RollingInterval.Day,
|
fileSizeLimitBytes: 1024 * 1024 * 10,
|
retainedFileCountLimit: 100,
|
outputTemplate: template,
|
restrictedToMinimumLevel: LogEventLevel.Warning))
|
// Error日志写入到文件
|
.WriteTo.Async(c => c.File(
|
path: "Logs/Error_.txt",
|
rollingInterval: RollingInterval.Day,
|
fileSizeLimitBytes: 1024 * 1024 * 10,
|
retainedFileCountLimit: 1000,
|
outputTemplate: template,
|
restrictedToMinimumLevel: LogEventLevel.Error))
|
.CreateLogger();
|
|
services.AddSerilog();
|
|
return services;
|
}
|
}
|
}
|