• abp vnext 微服务-基于Exceptionless实现分布式日志记录


    Exceptionless 是一个开源的实时的日志收集框架,它可以应用在基于 ASP.NET,ASP.NETCore,Web API,Web Forms,WPF,Console,ASP.NET MVC 等技术开发的应用程序中,并且提供了REST接口可以应用在 Javascript,Node.js 中。它将日志收集变得简单易用并且不需要了解太多的相关技术细节及配置,对于微服务架构的应用程序来说,统一的日志收集系统的建立更是有必要。
    
    下面介绍下  abp vnext 结合nlog输出日志到Exceptionless日志服务器
    
    1 、nuget 引用
      <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
        <PackageReference Include="NLog" Version="4.6.7" />
        <PackageReference Include="Exceptionless.AspNetCore" Version="4.3.2027" />
        <PackageReference Include="Exceptionless.NLog" Version="4.3.2027" />
    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"
          autoReload="true"
          throwConfigExceptions="true"
          internalLogLevel="Debug"
          internalLogToTrace="true">
    
      <extensions>
            <add assembly="Exceptionless.NLog" />
         
      </extensions>
    
      <targets>
    
        <!--<target xsi:type="file" name="logdashboardTraceLog" fileName="${basedir}/logs/${shortdate}.log"
              layout="${longdate}||${level}||${logger}||${message}||${exception:format=ToString:innerFormat=ToString:maxInnerExceptionLevel=10:separator=
    } || ${aspnet-traceidentifier} ||end" />-->
    
        <target xsi:type="file" name="logdashboardFile" fileName="${basedir}/logs/${shortdate}.log"
               layout="${longdate}||${level}||${logger}||${message}||${exception:format=ToString:innerFormat=ToString:maxInnerExceptionLevel=10:separator=
    }||end" />
    
        <target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}/${level}/${callsite:className=true:methodName=true:skipFrames=1}.log"
                    layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}"
                  maxArchiveFiles="10"
                  archiveAboveSize="10240"
                  archiveEvery="Day" />
        <target xsi:type="File" name="sqllogfile" fileName="${basedir}/logs/${shortdate}/${level}.log"
                  layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${stacktrace} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}"
                maxArchiveFiles="10"
                archiveAboveSize="10240000"
                archiveEvery="Day" />
    
        <target xsi:type="ColoredConsole" name="console"
                 layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}" />
    
        <target xsi:type="Null" name="blackhole" />
    
          <target xsi:type="Exceptionless" name="exceptionless">
                <field name="host" layout="${machinename}" />
                <field name="identity" layout="${identity}" />
              <!--  <field name="windows-identity" layout="${windows-identity:userName=True:domain=False}" />-->
                <field name="process" layout="${processname}" />
             
        </target>
      </targets>
    
      <rules>
    
        <!--<logger name="*" minlevel="Debug" writeTo="logdashboardTraceLog" />-->
    
        <logger name="*" minlevel="ERROR" writeTo="logdashboardFile" />
    
        <!-- 除非调试需要,把 .NET Core 程序集的 Debug 输出都屏蔽 Trace -》Debug-》 Information -》Warning-》 Error-》 Critical-->
        <logger name="Microsoft.*" minLevel="Trace" writeTo="blackhole" final="true" />
        <!-- 除非调试需要,把系统的 Debug 输出都屏蔽 -->
        <logger name="System.*" minLevel="Trace" writeTo="blackhole" final="true" />
    
        <logger name="*" minlevel="Info" writeTo="logfile,console" />
        <logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="sqllogfile" />
          <logger name="*" minlevel="ERROR" writeTo="exceptionless" />
      </rules>
    </nlog>
    3、 Program.cs 文件
      public class Program
        {
            public static void Main(string[] args)
            {
                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();
                }
            }
    
            internal static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    })
                    .UseAutofac()
                 .UseNLog();  // NLog: Setup NLog for Dependency injection;
        }
    4 、 OnApplicationInitialization 配置key、 地址
        var configuration = context.GetConfiguration();
                ExceptionlessClient.Default.Configuration.ApiKey = configuration.GetSection("Exceptionless:ApiKey").Value;
                //自己搭建的 Exceptionless 则配置对应的url
                //  ExceptionlessClient.Default.Configuration.ServerUrl = configuration.GetSection("Exceptionless:ServerUrl").Value;
                app.UseExceptionless();
    
    5、 测试
     public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
    
            public HomeController(ILogger<HomeController> logger)
            {
                _logger = logger;
                _logger.LogDebug(1, "NLog injected into HomeController");
            }
    
            public async Task<IActionResult> Index()
            {
                _logger.LogInformation("Hello, this is the index!");
                _logger.LogError(exception: new Exception("test"), message: "");
                var client = new HttpClient();
                await client.GetStringAsync("https://www.cnblogs.com/");
    
                return View();
            }
        }
    效果
    
    
    因为配置了输出方式为file 和exceptionless   所以可以在本地和日志服务器都看到对应的日志
    
    源代码
    https://gitee.com/conanOpenSource/abpexceptionless
    

      

  • 相关阅读:
    cordova build android get Execution failed for task ':dexArmv7Debug'
    brew install memcache get Error: Formulae found in multiple taps
    快速激活JetBrains系列产品
    NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
    `libsass` bindings not found. Try reinstalling `node-sass`?
    Cordova 快速入门记录
    perl: warning: Setting locale failed.
    httpclient源码分析之 PoolingHttpClientConnectionManager 获取连接
    httpclient源码分析之MainClientExec
    fastjson从1.1.41升级到1.2.28的坑
  • 原文地址:https://www.cnblogs.com/lyl6796910/p/12909746.html
Copyright © 2020-2023  润新知