1、添加引用nlog.config和Nlog.Web.AspNetCore
2、配置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"> <targets> <!--此部分中的所有目标将自动异步--> <target name="asyncFile" xsi:type="AsyncWrapper"> <!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"--> <target name="log_file" xsi:type="File" fileName="${basedir}/ProjectLogs/${shortdate}/${logger}-${level}-${shortdate}.txt" layout="${longdate} | ${message} ${onexception:${exception:format=message} ${newline} ${stacktrace} ${newline}" archiveFileName="${basedir}/archives/${logger}-${level}-${shortdate}-{#####}.txt" archiveAboveSize="102400" archiveNumbering="Sequence" concurrentWrites="true" keepFileOpen="false" /> </target> <!--使用可自定义的着色将日志消息写入控制台--> <target name="colorConsole" xsi:type="ColoredConsole" layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" /> </targets> <!--规则配置,final - 最终规则匹配后不处理任何规则--> <rules> <logger name="Microsoft.*" minlevel="Info" writeTo="" final="true" /> <logger name="*" minlevel="Info" writeTo="asyncFile" /> <logger name="*" minlevel="Warn" writeTo="colorConsole" /> </rules> </nlog>
3. 修改配置program
1 public class Program 2 { 3 public static void Main(string[] args) 4 { 5 CreateHostBuilder(args).Build().Run(); 6 7 var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 8 try 9 { 10 logger.Debug("init main"); 11 CreateHostBuilder(args).Build().Run(); 12 } 13 catch (Exception exception) 14 { 15 //NLog: catch setup errors 16 logger.Error(exception, "Stopped program because of exception"); 17 throw; 18 } 19 finally 20 { 21 // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) 22 NLog.LogManager.Shutdown(); 23 } 24 } 25 26 public static IHostBuilder CreateHostBuilder(string[] args) => 27 Host.CreateDefaultBuilder(args) 28 .ConfigureWebHostDefaults(webBuilder => 29 { 30 webBuilder.UseStartup<Startup>(); 31 }).ConfigureLogging(logging => 32 { 33 logging.ClearProviders(); // 这个方法会清空所有控制台的输出 34 logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); 35 }) 36 .UseNLog(); // 使用NLog; 37 }
4. 实例 在Web api中使用,跟VS自带的日志记录一样去使用
标签:core,CreateHostBuilder,Web,args,NLog,nlog,net,logger From: https://www.cnblogs.com/LaoMa0109/p/16810880.html