如何从logevent获取格式化的输出 [英] How to get formatted output from logevent

查看:44
本文介绍了如何从logevent获取格式化的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WriteTo.Observer 方法中,我想传递格式化的日志消息,因为它是使用格式模板呈现的.我该怎么办?

In the WriteTo.Observer method I want to pass the formatted log message as it is rendered using the formatting template. How might I accomplish that?

class Program
{
    static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.LiterateConsole()
            .WriteTo.RollingFile("log-{Date}.txt")
            .WriteTo.Observers(events => events.Do(evt => { Console.WriteLine($"Observed event {evt.MessageTemplate.Text}"); }).Subscribe())
            .WriteTo.Observers(events => events.Do(evt => { LogHandler(evt.MessageTemplate.Text);}).Subscribe())
            .CreateLogger();

        Log.Logger.Information("Log msg from Main");
        Console.ReadLine();
    }

    public static void LogHandler(string logMsg)
    {
        Console.WriteLine("LogHandler: " + logMsg); //I want the complete formatted log message as it would appear in a file i.e. "[10:20:14 INF] Log msg from DoNothing"
    }
}

推荐答案

我设法自己解决了所有这些,以及我对Serilog遇到的其他几个问题.

I managed to resolve this all by myself as well as a couple of other questions I had about Serilog.

我最初发布了关于NLog的这个问题,并且在解决它的过程中我发现了Serilog.我很高兴我做到了.

I originally posted this question about NLog and in the process of resolving it I discovered Serilog. I'm glad I did.

此答案说明了几个概念:

This answer illustrates several concepts:

1.)从记录器中调用自定义处理程序

1.) Calling a custom handler from the Logger

2.)格式化日志消息

2.) Formatting the log message

3.)在日志消息中包括调用方法的名称.感谢和感谢,请访问@ MovGP0以获取

3.) Including calling method name in the log message. Thanks and credit go to @MovGP0 for his answer found here.

class Program
{
    static void Main(string[] args)
    {
        var outputTemplate = "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}in method {MemberName} at {FilePath}:{LineNumber}{NewLine}{Exception}{NewLine}";
        Serilog.Formatting.Display.MessageTemplateTextFormatter tf = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture);

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.CustomSink(tf, LogHandler)
            .CreateLogger();

        Log.Logger.Here().Information("Hello world");
        Console.ReadLine();
    }

    public static void LogHandler(string logMsg)
    {
        Console.WriteLine("LogHandler: " + logMsg); 
    }
}


public class CustomSink : ILogEventSink
{
    private readonly ITextFormatter _formatter;
    private readonly Action<string>[] _handlers;

    public CustomSink(ITextFormatter formatter, params Action<string>[] handlers)
    {
        _formatter = formatter;
        _handlers = handlers;
    }

    public void Emit(LogEvent logEvent)
    {
        var buffer = new StringWriter(new StringBuilder(256));
        _formatter.Format(logEvent, buffer);
        string message = buffer.ToString();

        foreach (Action<string> handler in _handlers)
            handler(message);
    }
}


public static class MySinkExtensions
{
    public static LoggerConfiguration CustomSink(
              this LoggerSinkConfiguration loggerConfiguration,
              ITextFormatter formatter = null, params Action<string>[] handlers)
    {
        return loggerConfiguration.Sink(new CustomSink(formatter, handlers));
    }


    public static ILogger Here(this ILogger logger,
    [CallerMemberName] string memberName = "",
    [CallerFilePath] string sourceFilePath = "",
    [CallerLineNumber] int sourceLineNumber = 0)
    {
        return logger
            .ForContext("MemberName", memberName)
            .ForContext("FilePath", sourceFilePath)
            .ForContext("LineNumber", sourceLineNumber);
    }

}

这篇关于如何从logevent获取格式化的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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