- 新建webapi
- 添加Nlog nuget包引用
- 添加Nlog配置文件
<?xml version="1.0" encoding="utf-8"?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Warn" internalLogFile="internal-nlog.txt"> <extensions> <!--enable NLog.Web for ASP.NET Core--> <add assembly="NLog.Web.AspNetCore"/> </extensions> <!-- define various log targets --> <!--定义日志文件目录--> <variable name="logDirectory" value="${basedir}/logs/${shortdate}"/> <variable name="nodeName" value="node1"/> <targets async="true"> <!-- 全部日志target --> <target xsi:type="File" name="allfile" fileName="${logDirectory}/nlog-all/${shortdate}.log" layout="#node1#${longdate}#${logger}#${uppercase:${level}}#${callsite}#${callsite-linenumber}#${aspnet-request-url}#${aspnet-request-method}#${aspnet-mvc-controller}#${aspnet-mvc-action}#${message}#${exception:format=ToString}#" keepFileOpen="false" /> <!-- 本地文件日志target --> <target xsi:type="File" name="ownLog-file" fileName="${logDirectory}/nlog-${level}/${shortdate}.log" layout="#${longdate}#${nodeName}#${logger}#${uppercase:${level}}#${callsite}#${callsite-linenumber}#${aspnet-request-url}#${aspnet-request-method}#${aspnet-mvc-controller}#${aspnet-mvc-action}#${message}#${exception:format=ToString}#" keepFileOpen="false" /> <!-- Tcp日志target --> <target xsi:type="Network" name="ownLog-tcp" keepConnection="false" address ="tcp://192.168.3.10:5000" layout="#${longdate}#${nodeName}#${logger}#${uppercase:${level}}#${callsite}#${callsite-linenumber}#${aspnet-request-url}#${aspnet-request-method}#${aspnet-mvc-controller}#${aspnet-mvc-action}#${message}#${exception:format=ToString}#" /> <!--grok 规则--> <!--%#{DATA:request_time}#%{DATA:node_name}#%{DATA:class_name}#%{DATA:log_level}#%{DATA:call_site}#%{DATA:line_number}#%{DATA:request_url}#%{DATA:request_method}#%{DATA:container_name}#%{DATA:action_name}#%{DATA:log_info}#%{DATA:exception_msg}#--> <!--空白--> <target xsi:type="Null" name="blackhole" /> </targets> <!--日志级别 Trace -》Debug-》 Info -》Warn-》 Error-》 Fatal--> <!--日志规则--> <rules> <!--全部日志, 包括Microsoft日志--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--自定义日志,排除Microsoft日志--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Debug" writeTo="ownLog-file" /> <logger name="*" minlevel="Info" writeTo="ownLog-tcp" /> </rules> </nlog>
- startup添加中间件
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog; using NLog.Extensions.Logging; using NLog.Web;namespace UserWebApplication { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var currentClassLogger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); services.AddSingleton(currentClassLogger); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime lifetime) { //loggerFactory.AddNLog(); //loggerFactory.ConfigureNLog("nlog.config"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); //停止时注销 lifetime.ApplicationStopped.Register(() => { //Nlog 确保在应用程序退出之前刷新并停止内部计时器/线程(避免Linux上出现分段错误) LogManager.Shutdown(); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
- Program 添加Loggin配置
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog.Web; namespace UserWebApplication { 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.UseStartup<Startup>(); }).ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }).UseNLog(); } }
- 修改appsetting.json 配置
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Trace", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
- 使用示例
private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); _logger.LogInformation("这是一条测试消息Information"); _logger.LogError("这是一条测试消息Erro"); _logger.LogDebug("这是一条测试消息Debug"); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); }
参考自https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-2