log4net + appsettings.json
log4net.config配置
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="DebugAppender" type="log4net.Appender.RollingFileAppender,log4net">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
</filter>
<file value="Logs/" />
<encoding value="utf-8"/>
<preserveLogFileNameExtension value="true" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<countDirection value="1" />
<maxSizeRollBackups value="-1"/>
<maximumFileSize value="100MB"/>
<datePattern value="yyyy-MM-dd"/Debug.log"" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender,log4net">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
<file value="Logs/" />
<encoding value="utf-8"/>
<preserveLogFileNameExtension value="true" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<countDirection value="1" />
<maxSizeRollBackups value="-1"/>
<maximumFileSize value="100MB"/>
<datePattern value="yyyy-MM-dd"/Info.log"" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<appender name="WarnAppender" type="log4net.Appender.RollingFileAppender,log4net">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
</filter>
<file value="Logs/" />
<encoding value="utf-8"/>
<preserveLogFileNameExtension value="true" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<countDirection value="1" />
<maxSizeRollBackups value="-1"/>
<maximumFileSize value="100MB"/>
<datePattern value="yyyy-MM-dd"/Warn.log"" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender,log4net">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="FATAL" />
</filter>
<file value="Logs/" />
<encoding value="utf-8"/>
<preserveLogFileNameExtension value="true" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<countDirection value="1" />
<maxSizeRollBackups value="-1"/>
<maximumFileSize value="100MB"/>
<datePattern value="yyyy-MM-dd"/Error.log"" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ManagedColoredConsoleAppender">
<mapping>
<level value="FATAL" />
<level value="ERROR" />
<foreColor value="Red" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Green" />
</mapping>
<mapping>
<level value="INFO" />
<level value="DEBUG" />
<foreColor value="White" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
</layout>
</appender>
<appender name="ConsoleForwardingAppender" type="log4net.Appender.ForwardingAppender" >
<threshold value="WARN"/>
<appender-ref ref="ColoredConsoleAppender" />
</appender>
<root>
<!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->
<level value="ALL" />
<appender-ref ref="DebugAppender" />
<appender-ref ref="InfoAppender" />
<appender-ref ref="WarnAppender" />
<appender-ref ref="ErrorAppender" />
<appender-ref ref="ConsoleForwardingAppender"/>
</root>
</log4net>
appsettings.json
{
"Swagger": {
"Version": "1.01",
"Name": "MicroserviceName"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"System": "Warning",
"Microsoft": "Warning",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning", // 提供给第三方调用API日志
"Microsoft.Hosting.Lifetime": "Warning",
"System.Net.Http.HttpClient": "Warning", // 记录内部http请求
"System.Net.Http.HttpClient.Default.ClientHandler": "None",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
"Microsoft.EntityFrameworkCore.Database.Connection": "Warning"
},
"Debug": {
"LogLevel": {
//级别,由高到低: "ERROR"、"Warning"、"Information"、"DEBUG"
"Default": "Information"
}
},
"Console": {
"LogLevel": {
"Default": "ERROR"
}
}
},
"AllowedHosts": "*"
}
log4net初始化
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddLog4Net(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls("http://*:port");
});
}
}
Swagger设置
public void ConfigureServices(IServiceCollection services)
{
// 增加Swagger文档界面
string version = _configuration["Swagger:Version"];
string name = _configuration["Swagger:Name"];
services.AddSwaggerGen(c =>
{
c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.ActionDescriptor.RouteValues["action"]}");
c.SwaggerDoc(name, new OpenApiInfo { Title = name, Version = version, });
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
// swagger鉴权
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
string version = _configuration["Swagger:Version"];
string name = _configuration["Swagger:Name"];
app.UseSwagger(s =>
{
s.SerializeAsV2 = true;
s.RouteTemplate = "swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(s =>
{
s.DocumentTitle = name + "接口说明";
s.SwaggerEndpoint($"/swagger/{name}/swagger.json", name);
});
}
其中,swagger生成的xml,取消注释警告
可访问swagger:http://localhost:port/swagger
高速写日志
LogHelper.Instance().Register();
LogHelper.Debug("Debug");
LogHelper.Info("Info");
LogHelper.Warn("Warn");
LogHelper.Error("Error");
其中,LogHelper由ManualResetEvent具体应用实现。