随笔 - 216  文章 - 0 评论 - 2 阅读 - 24万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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} \nTime: {Timestamp:yyyy-MM-dd HH:mm:ss.fff} \nLevel: {Level:u3} \nMessage: {Message:lj} \n{Exception} \n"
        }
      },
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://172.22.113.77:5341"
        }
      }
    ]
  }
}
logsettings.json
复制代码

 

 

 

参考: Serilog 入门官方文档

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

参考3:Seq 日志删除

 

  

 

posted on   青叶煮酒  阅读(598)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示