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
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } 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(); // 使用NLog; }
标签:core,CreateHostBuilder,logger,args,NLog,nlog,net,public From: https://www.cnblogs.com/superfeeling/p/16748282.html