我可以使用Serilog登录到单独的文件吗? [英] Can I log to separate files using Serilog?

查看:68
本文介绍了我可以使用Serilog登录到单独的文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ASP.NET Core 2.1应用程序将所有常用内容"记录到Serilog文件接收器,即与应用程序相关的内容,例如调试,监视,性能等.

My ASP.NET Core 2.1 app logs to a Serilog file sink, all the "usual stuff" - i.e. app related stuff such as debug, monitoring, performance, etc.

但是,我们还需要将其他数据记录到单独的文件中.与应用无关,但与客户有关-应该放入数据库中的内容.但是,由于遗留原因,该系统上没有数据库,因此需要将数据保存到文件中.显然,这不能写入相同的日志文件.

However we also need to log other data to a separate file. Not app related, but customer related - the kind of stuff that should go into a database. However for legacy reasons, there is no database on this system and so that data needs to be saved to a file instead. Obviously this can't be written to the same log file.

我可以只写一个FileStream.但是我更喜欢使用Serilog进行结构化日志记录.

I could just write to a FileStream. But I prefer to do structured logging with Serilog.

那么有没有办法同时拥有两个记录器?哪个将不同的数据记录到不同的文件接收器.

So is there a way to have two loggers simultaneously? Which log different data to different file sinks.

(如果是这样,我如何将它们注入到班级中-现在我只需注入ILogger<ClassName>.)

(If so, how do I inject them into my classes - right now I just inject ILogger<ClassName>.)

推荐答案

您绝对可以做到这一点.

You can definitely do that.

  1. 您需要导入软件包 Serilog.Sinks.File

然后,您必须配置Serilog.

Then you have to configure Serilog.

在program.cs中执行以下操作.

In program.cs do following thing.

Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
    .WriteTo.File(
        @"<<your log file path>>",
    fileSizeLimitBytes: 10000000,
    rollOnFileSizeLimit: true,
    shared: true,
    flushToDiskInterval: TimeSpan.FromSeconds(1))
        .CreateLogger();

在buildWebHost函数中添加UseSerilog().

In buildWebHost function add UseSerilog().

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
        .UseSerilog() // <-- Add this line
        .Build();

更新1

我已经使用了EventId属性.这只是一个演示,演示了如何基于eventId使用不同的文件,但根据您的要求,您必须自己实现其他功能.

I have used EventId property. This is just demo that how you can use different file based on eventId but for your requirement you have to implement additional thing your own.

Program.cs

Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Logger(cc => cc.Filter.ByIncludingOnly(WithProperty("EventId",1001)).WriteTo.File("Test1001.txt",flushToDiskInterval: TimeSpan.FromSeconds(1)))
                .WriteTo.Logger(cc => cc.Filter.ByIncludingOnly(WithProperty("EventId", 2001)).WriteTo.File("Test2001.txt", flushToDiskInterval: TimeSpan.FromSeconds(1)))
                .CreateLogger();

            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args).UseSerilog()
                .UseStartup<Startup>();

        public static Func<LogEvent, bool> WithProperty(string propertyName, object scalarValue)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");           
            ScalarValue scalar = new ScalarValue(scalarValue);
            return e=>
            {
                LogEventPropertyValue propertyValue;
                if (e.Properties.TryGetValue(propertyName, out propertyValue))
                {
                    var stValue = propertyValue as StructureValue;
                    if (stValue != null)
                    {
                        var value = stValue.Properties.Where(cc => cc.Name == "Id").FirstOrDefault();
                        bool result = scalar.Equals(value.Value);
                        return result;
                    }
                }
                return false;
            };
        }
    }

我的HomeController.cs

My HomeController.cs

  public class HomeController : Controller
    {
        ILogger<HomeController> logger;
        public HomeController(ILogger<HomeController> logger)
        {
            this.logger = logger;
        }
        public IActionResult Index()
        {
            logger.Log(LogLevel.Information,new EventId(1001), "This is test 1");
            logger.Log(LogLevel.Information, new EventId(2001), "This is test 2");
            return View();
        } 
    }

注意:主要是您必须使用某种类型的过滤器.

这篇关于我可以使用Serilog登录到单独的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆