Serilog增强器无法记录到控制台(.Net 6.0)

3

使用(.Net 6.0) 我尝试输出一些额外的默认信息与所有日志 当我输出到控制台时,我看不到属性,但如果我启用Json并输出到文件,则一切正常。想知道你是否有任何线索?

public class Program
{
    public static int Main(string[] args)
    {

        var builder = WebApplication.CreateBuilder(args);

        Log.Logger = new LoggerConfiguration()
            //.WriteTo.File(new Serilog.Formatting.Json.JsonFormatter(), "Logs/log-.txt", fileSizeLimitBytes: 5242880, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day, shared: true)
            .Enrich.FromLogContext()
            .Enrich.WithProcessId()
            .Enrich.WithProcessName()
            .Enrich.WithProperty("Prop1", "ABC123")
            .Enrich.WithProperty("Prop2", "1.00")
            .Enrich.WithProperty("PID", Process.GetCurrentProcess().Id)
            .WriteTo.Console()
            .CreateLogger();


        builder.Host.UseSerilog(); 

        // Add services to the container.

        var app = builder.Build();

        // Configure the HTTP request pipeline.
    
        app.MapGet("/weatherforecast", () =>
        {
            Log.Information("Hello....");
            return forecast;
        });

        try
        {
            app.Run();
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
        finally
        {
            Log.CloseAndFlush();
        }

        return 0;
    }
}

示例是默认的 .Net 6.0 API(Web 和 Console -> App -> ASP.Net Core)。 - Sumonto
1个回答

5

您必须将这些属性包含在Console输出的模板中。
占位符通过名称匹配;对于给定的示例,请使用{Prop1},{Prop2}和{PID}

Log.Logger = new LoggerConfiguration()    
    .Enrich.FromLogContext()
    .Enrich.WithProcessId()
    .Enrich.WithProcessName()
    .Enrich.WithProperty("Prop1", "ABC123")
    .Enrich.WithProperty("Prop2", "1.00")
    .Enrich.WithProperty("PID", Process.GetCurrentProcess().Id) // 9840
    .WriteTo.Console(
        outputTemplate: "{Timestamp:HH:mm:ss} {Level:u3} {Message} {Prop1} {Prop2} {PID}{NewLine}{Exception}"        
    )
    .CreateLogger();

输出:

23:10:40 INF Hello.... ABC123 1.00 9840

感谢您的帮助。 对于Json类型: .WriteTo.File(new Serilog.Formatting.Json.JsonFormatter(), "Logs/log-.txt", 有没有一种方法可以在不添加子属性:{}类型的情况下完成相同的操作? - Sumonto
参见:https://nblumhardt.com/2021/06/customize-serilog-text-output/#-listing-only-hidden-properties-not-otherwise-present-in-the-message-or-template(_Serilog.Expressions_格式化具有一些更新/更复杂的选项,可包括属性。) - Nicholas Blumhardt
1
还有一件事情没有被提到,可能会涵盖在outputTemplate中的{Properties},它将发出所有尚未被单独引用的属性(请参见参考资料)。 (当然,尼克的评论很可能是你特别想要的) - Ruben Bartelink
嗨@NicholasBlumhardt,想问一下您是否能为https://stackoverflow.com/questions/73942087/file-sink-output-very-different-than-console-for-json提供一些建议? - Sumonto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接