1

这是扩展方法

public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app)
{
    //add serilog https://github.com/serilog/serilog-extensions-logging
    // https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
    Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

    var startTime = DateTimeOffset.UtcNow;

    Log.Logger.Information("Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);

    return app;
}

我们可以Startup像这样使用它

app.UseLoggerConfig();

我想保存日志\\%windir%\log\callingAppName\logfile.log

任何想法我们怎么能做到这一点?

4

1 回答 1

1

我认为您可以检查托管环境以获取此类信息。

IHostingEnvironment.ApplicationName

获取或设置应用程序的名称。此属性由主机自动设置为包含应用程序入口点的程序集

强调我的

鉴于这是要共享的,它应该从它被使用/调用的地方显式注入。即应用程序运行的网络托管环境。

public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app, IHostingEnvironment env) {

    var callingAppName = env.ApplicationName;

    var path = $"{callingAppName}/logfile.log";

    //add serilog https://github.com/serilog/serilog-extensions-logging
    // https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
    Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.File(path, rollingInterval: RollingInterval.Day)
    .CreateLogger();

    var startTime = DateTimeOffset.UtcNow;

    Log.Logger.Information("Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);

    return app;
}

我们可以Startup像这样使用它

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

    //...code removed for brevity

    app.UseLoggerConfig(env);
}

这也将允许更改基于日志记录位置的环境类型,如开发、登台、生产等。

public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app, IHostingEnvironment env) {

    var callingAppName = env.ApplicationName;

    var path = $"{callingAppName}/logfile.log";
    if (env.IsDevelopment()) {
        // In Development logging path
    } else {
        // In Staging/Production logging path
    }

    //add serilog https://github.com/serilog/serilog-extensions-logging
    // https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
    Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.File(path, rollingInterval: RollingInterval.Day)
    .CreateLogger();

    var startTime = DateTimeOffset.UtcNow;

    Log.Logger.Information("Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);

    return app;
}
于 2018-03-03T19:15:38.003 回答