.Net 6 Webapi Core 添加日志管理(Serilog),将日志输出到控制台、数据库、文本文件中

目录

首先引用配置Serilog的NueGet包

Program.cs  添加如下代码

 使用方法

测试应用


  • 首先引用配置Serilog的NueGet包

Serilog

Serilog.AspNetCore

Serilog.Formatting.Compact

Serilog.Sinks.File

Serilog.Sinks.MySQL

 

  • Program.cs  添加如下代码

先封装一个类:

这里的将日志输出到数据库我给注释掉了,需要的伙伴可以解除注释哦

 public static class InitScoped
    {
        /// <summary>
        /// 注入容器
        /// </summary>
        /// <param name="services"></param>
        public static void Register(this IServiceCollection services) 
        {
            services.AddScoped<BllTarget,DalTarget>();
        }
        /// <summary>
        /// Serilog 日志拓展
        /// </summary>
        public static void ConfigureLogging(WebApplicationBuilder builder)
        {
            string dateFile = DateTime.Now.ToString("yyyyMMdd");

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Console(new CompactJsonFormatter())
                //.WriteTo.MySQL(connectionString: builder.Configuration.GetConnectionString("DbConnectionString"), tableName: "Logs") // 输出到数据库
                .WriteTo.Logger(configure => configure
                    .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
                    .WriteTo.File(
                        $"logs/log-debug-{dateFile}.txt",
                        rollingInterval: RollingInterval.Day,
                        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
                .WriteTo.Logger(configure => configure
                    .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)
                    .WriteTo.File(
                        $"logs/log-info-{dateFile}.txt",
                        rollingInterval: RollingInterval.Day,
                        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
                .WriteTo.Logger(configure => configure
                    .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
                    .WriteTo.File(
                        $"logs/log-error-{dateFile}.txt",
                        rollingInterval: RollingInterval.Day,
                        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
                .WriteTo.File(
                    $"logs/log-total-{dateFile}.txt",
                    rollingInterval: RollingInterval.Day,
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
                    restrictedToMinimumLevel: LogEventLevel.Debug)
                .CreateLogger();
        }
    }

Program.cs 调用此方法

#region 配置Serilog 日志
InitScoped.ConfigureLogging(builder);
builder.Host.UseSerilog(); //向主机注册Serilog
#endregion

 

 

 

  •  使用方法

直接在需要使用的控制器或方法类下进行注入即可,示例代码如下

 public class DalTarget : BllTarget
    {
        private readonly ServerContext _context;
        private readonly ILogger<DalTarget> _logger;
        public DalTarget(ServerContext context, ILogger<DalTarget> logger)
        {
            _context = context;
            _logger = logger;
        }
        public async Task<List<Target>> GetTarget(Guid guid)
        {
            try
            {
                var data = await _context.Targets.Where(s => s.Id ==     guid).AsNoTracking().ToListAsync();
                if (data.Count <= 0)
                {
                    throw new Exception("接口:GetTarget|报错:查询列表id返回空数据");
                }
                return data;
            }
            catch (Exception ex)
            {

                _logger.LogInformation($"GetTarget:{ex.Message},参数|id:{guid}");
                _logger.LogError($"GetTarget:{ex.Message},参数|id:{guid}");
                throw new Exception(ex.Message);
            }

        }

       
      
    }

这里 的LogInformation 和  LogError  看情况写  我把两个都写出来了  

  • 测试应用

 报错后会在项目地址自动创建log文件夹

 控制台输出

好啦,今天分享到这里哦  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农小小涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值