获取没有 DI 的 Serilog 记录器的实例 [英] Getting an instance of the Serilog logger without DI

查看:104
本文介绍了获取没有 DI 的 Serilog 记录器的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有依赖注入的控制台应用程序,它使用 log4net.我正在尝试用 Serilog 替换 log4net.

I have a console app without dependency injection that uses log4net. I'm trying to replace log4net with Serilog.

这与 log4net 的设置方式很接近:

This is close to how log4net is setup:

using log4net;
using log4net.Config;
using System;
using System.IO;
using System.Reflection;

namespace LoggingDemo.Log4Net
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));
        static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            log.Debug("Starting up");
            log.Debug("Shutting down");
            Console.ReadLine();
        }
    }
}

在其他类中通过设置private static readonly ILog log = LogManager.GetLogger(typeof(Program));

Serilog 设置如下:

Serilog is setup like this:

using Serilog;
using System;

namespace LoggingDemo.Serilog
{
    class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logfile.log", rollingInterval: RollingInterval.Day)
                .CreateLogger();

            Log.Debug("Starting up");
            Log.Debug("Shutting down");

            Console.ReadLine();
        }
    }
}

如何像我们在其他类中使用 log4net 那样获取 Serilog 记录器的实例,即 private static readonly ILog log = LogManager.GetLogger(typeof(Program));?

How can I get an instance of the Serilog logger like we do with log4net in other classes, i.e private static readonly ILog log = LogManager.GetLogger(typeof(Program));?

推荐答案

Serilog 允许用事件的来源来标记事件,一般来说是编写它们的类的名称.您可以使用 Log 类的 ForContext 方法之一来做到这一点.

Serilog allows events to be tagged with their source, generally speaking the name of the class writing them. You can do that using one of the ForContext methods of the Log class.

在你上面的例子中,它会是这样的:

In your examples above, it would something like this:

private static readonly ILogger log = Log.ForContext<Program>();

private static readonly ILogger log = Log.ForContext(typeof(Program));

写入的事件将包含一个属性 SourceContext,其值为 "MyNamespace.MyClass",稍后可用于过滤掉嘈杂的事件,或有选择地将它们写入特定的下沉.

The event written will include a property SourceContext with value "MyNamespace.MyClass" that can later be used to filter out noisy events, or selectively write them to particular sinks.

文档:https://github.com/serilog/serilog/wiki/Writing-Log-Events#source-contexts

这篇关于获取没有 DI 的 Serilog 记录器的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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