zoukankan      html  css  js  c++  java
  • 结构化日志工具 Serilog 使用

    1. 添加 NuGet 包

      在解决方案管理器视图中的目标项目上右键  -> 管理 NuGet 程序包;

      添加 Serilog、Serilog.Sinks.Console、Serilog.Sinks.File、Serilog.Sinks.Seq、Serilog.AspNetCore、Microsoft.Extensions.Configuration.Json 包,如下图所示:

    2. 安装日志监控组件 Seq

     下载地址:https://datalust.co/download

      

     安装完成后,打开:http://172.22.113.77:5341 验证是否成功安装(IP 为 Seq 安装电脑的 IP)。

     注:该程序安装完成后以服务的形式运行,如下图所示:

      

    3. 通过代码使用

    using Microsoft.Extensions.Configuration;
    using Serilog;
    using Serilog.Core;
    using Serilog.Events;
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace SerilogDemo
    {
        class Program
        {
            static string logConfigFilePath = "Config//logsettings.json";
    
            static void Main(string[] args)
            {
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile(path: logConfigFilePath, optional: false, reloadOnChange: true)
                    .Build();
    
                Log.Logger = new LoggerConfiguration()
                    .Enrich.With(new ThreadIdEnricher())
                    .Enrich.With(new IpAddressEnricher())
                    .ReadFrom.Configuration(configuration)
                    .CreateLogger();
    
                Log.Information("Serilog test start. {Name}", Environment.UserName);
    
                Thread thread = new Thread(Thread_Test);
                thread.Start();
    
                int a = 10, b = 0;
                try
                {
                    Log.Debug("Dividing {A} by {B}", a, b);
                    Console.WriteLine(a / b);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Something went wrong");
                }
                finally
                {
                    Log.CloseAndFlush();
                }
    
                Console.ReadLine();
            }
    
            private static void Thread_Test()
            {
                Log.Debug("Thread_Test() In.");
                Console.WriteLine("ThreadId = {0}", Thread.CurrentThread.ManagedThreadId);
                Log.Debug("Thread_Test() Out.");
            }
        }
    
        class ThreadIdEnricher : ILogEventEnricher
        {
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                        "ThreadId", Thread.CurrentThread.ManagedThreadId));
            }
        }
    
        class IpAddressEnricher : ILogEventEnricher
        {
            string localIp = "";
    
            public IpAddressEnricher()
            {
                localIp = GetLocalIp();
            }
    
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                        "IpAddress", localIp));
            }
    
            private string GetLocalIp()
            {
                string hostname = Dns.GetHostName();
                IPHostEntry localhost = Dns.GetHostEntry(hostname);
                if (localhost != null)
                {
                    foreach (IPAddress item in localhost.AddressList)
                    {
                        //判断是否是内网IPv4地址
                        if (item.AddressFamily == AddressFamily.InterNetwork)
                        {
                            return item.MapToIPv4().ToString();
                        }
                    }
                }
                return "127.0.0.1";
            }
        }
    }
    View Code
    {
      "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
        "MinimumLevel": "Debug",
        "WriteTo": [
          {
            "Name": "Console",
            "Args": {
              "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Colored, Serilog.Sinks.Console",
              "outputTemplate": "{Level:u3}: {Message}{NewLine}{Exception}"
            }
          },
          {
            "Name": "File",
            "Args": {
              "path": "Logs/AEConsoleGatewayService_.log",
              "rollingInterval": "Day",
              "outputTemplate": "Thread ID: {ThreadId} 
    Time: {Timestamp:yyyy-MM-dd HH:mm:ss.fff} 
    Level: {Level:u3} 
    Message: {Message:lj} 
    {Exception} 
    "
            }
          },
          {
            "Name": "Seq",
            "Args": {
              "serverUrl": "http://172.22.113.77:5341"
            }
          }
        ]
      }
    }
    logsettings.json

    参考: Serilog 入门官方文档

    参考2:Seq 官方文档 1   Seq官方文档 2

    参考3:Seq 日志删除

      

  • 相关阅读:
    回调函数: 一定要在函数名前加上 CALLBACK,否则有可能引起内存崩溃!
    win32-api: 让 static 控件中的水平横行,垂直居中。
    Win32-API: 终于能正常的捕获焦点事件: WM_COMMAND、BN_SETFOCUS、EN_SETFOCUS
    FindExecutable:查找与一个指定文件关联在一起的程序的文件名
    ImageMagick: win7 | win8 & uac (用户帐户控制) 注册表的一些事
    ImageMagick: 6.8.3 升级到 6.8.9 遇到的问题
    ImageMagick: DrawImage(Image*,DrawInfo*) 绘制填充图片时卡住的原因分析
    真的无语, 今天遇到一个奇葩的事情: http 会话劫持
    高DPI下界面错乱的解决方法和原理
    关于 HDC 的释放
  • 原文地址:https://www.cnblogs.com/dhqy/p/14448201.html
Copyright © 2011-2022 走看看