首页 > 其他分享 >.net Core API 添加 NLog

.net Core API 添加 NLog

时间:2023-07-05 10:24:17浏览次数:35  
标签:Core exception logging args public NLog net logger

nlog.config

<?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="Info"
      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">
​
  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
​
  <!-- the targets to write to -->
  <targets>
    <!-- File Target for all log messages with basic details -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
​
    <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />
​
    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
  </targets>
​
  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
​
    <!--Output hosting lifetime messages to console target for faster startup detection -->
    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
​
    <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
​
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

program.cs 

public class Program
    {
        public static void Main(string[] args)
        {
            var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().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: Setup NLog for Dependency injection
    }

 

标签:Core,exception,logging,args,public,NLog,net,logger
From: https://www.cnblogs.com/hofmann/p/17527802.html

相关文章

  • Sentieon | 每周文献-Genetic Disease-第二期
    遗传病系列文章-1标题(英文):AnswerALS,alarge-scaleresourceforsporadicandfamilialALScombiningclinicalandmulti-omicsdatafrominducedpluripotentcelllines标题(中文):AnswerALS,一种用于散发性和家族性ALS的大规模资源,结合了来自诱导多能细胞系的临床和多......
  • Noisy Networks for Exploration
    郑重声明:原文参见标题,如有侵权,请联系作者,将会撤销发布!PublishedasaconferencepaperatICLR2018ABSTRACT 1INTRODUCTION 2BACKGROUND 2.1MARKOVDECISIONPROCESSESANDREINFORCEMENTLEARNING 2.2DEEPREINFORCEMENTLEARNING ......
  • .Net下验证MongoDB 的 Linq 模式联合查询是否可用
    MongoDB.Driver类库提供了Linq查询的支持。然而,在使用Linq进行联合查询时,是否能够正确转换为MongoDB底层的查询语句还有待验证。今天,我将进行实验来验证一下。输出查询语句首先,通过订阅MongoClientSettings的功能,将查询语句输出。varsettings=MongoCli......
  • asp.net core如何获取客户端IP地址
    客户端直接访问服务器直接通过HttpContext.Connection.RemoteIpAddress获取客户端Ip[HttpGet][Route("GetClientIP")]publicasyncTask<IActionResult>GetClientIP(){ varip4=HttpContext.Connection.RemoteIpAddress.MapToIPv4(); returnOk(ip4.ToString());}客......
  • 如何将SSL证书从Kubernetes Secrets导出并复原为证书PEM和密钥文件
    首先,您需要使用kubectl工具从Kubernetes导出Secret到一个yaml文件,这通常使用如下命令:kubectlgetsecretmy-secret-oyaml>my-secret.yaml然后我们可以创建一个简单的bash脚本来处理yaml文件并导出证书:#!/bin/bash#解析yaml文件并得到证书内容certData=......
  • windows下mysql中binlog日志分析和数据恢复
    1.首先查看是否开启了binlogshowvariableslike'%log_bin%'; 我的已经开启了,如果没开启则开启binlog2.查看有哪些binlog文件和正在使用的binlog文件 查看有哪些binlog文件showbinarylogs;或者showmasterlogs; 查看当前正在使用的是哪一个binlog文件show......
  • 【Netty】「萌新入门」(三)ChannelFuture 与 CloseFuture
    前言本篇博文是《从0到1学习Netty》中入门系列的第三篇博文,主要内容是介绍Netty中ChannelFuture与CloseFuture的使用,解决连接问题与关闭问题,往期系列文章请访问博主的Netty专栏,博文中的所有代码全部收集在博主的GitHub仓库中;连接问题与ChannelFuture在Netty中,所有的......
  • Vue-CoreVideoPlayer使用
    介绍Vue-CoreVideoPlayer一款基于vue.js的轻量级的视频播放器插件。采用AdobdXD进行UI设计,支持移动端适配,不仅功能强大,颜值也是超一流!Vue-CoreVideoPlayer的说明文档和sample都很完善,上手十分容易。该组件也保持了和原生HTMLVideo属性配置的对接,可定制性很高。播放器......
  • MQTTnet 创建基于 WebSocket 的 Mqtt 服务器
    MQTTnet.Exceptions.MqttProtocolViolationException:Expectedatleast21540bytesbutthereareonly71bytes使用了错误的协议,mqtt有tcp和ws两种连接协议ws://使用1883端口就能正常连接 ......
  • efficienthrnet读取H-2yaml文件
    代码读取配置文件创建的网络['features.0.1.weight:torch.Size([24,3,3,3])','features.0.2.weight:torch.Size([24])','features.0.2.bias:torch.Size([24])','features.1.conv.0.1.weight:torch.Size([24,1,3,3])','features.1.......