Once you reach the stage of deploying your code to the cloud, such as AWS, you’ll probably want to use a log file aggregator to make management and security easier. But we found that it’s not always easy to figure out which log file you’re looking for based on the default name, which will be something like SCF.20190228.123e4567-e89b-12d3-a456-426655440000.log.txt. It does give us the date that the log file was started, but that’s about it. Luckily, it’s easy to customise the log file name by making changes to the engine Startup.cs file in the engine project.

In there, you’ll find a block like this:

Log.Logger = new LoggerConfiguration()
              .ReadFrom.Configuration(this.Configuration)
              .Enrich.FromLogContext()
              .Enrich.With(new ScLogEnricher())
              .WriteTo.Async(a => a.File(
                  $@"{Path.Combine(this._hostEnv.WebRootPath, "logs")}\SCF.{DateTimeOffset.UtcNow:yyyyMMdd}.log.{this._nodeInstanceId}.txt",
                  this.GetSerilogLogLevel(),
                  "{ThreadId} {Timestamp:HH:mm:ss} {ScLevel} {Message}{NewLine}{Exception}",
                  fileSizeLimitBytes: fileSize,
                  rollOnFileSizeLimit: true), bufferSize: 500)
              .CreateLogger();

The sixth line tells us the exact path that the log file will be written to, and that’s the one we want to change.

Here is our updated version.

var environmentName = this.Configuration.GetSection("AppSettings:EnvironmentName")?.Value;
var logFileName =
    $@"{Path.Combine(this._hostEnv.WebRootPath, "logs")}\SCF.{environmentName}.{DateTimeOffset.UtcNow:yyyy-MM-dd-HHmmss}.log.txt";

Log.Logger = new LoggerConfiguration()
              .ReadFrom.Configuration(this.Configuration)
              .Enrich.FromLogContext()
              .Enrich.With(new ScLogEnricher())
              .WriteTo.Async(a => a.File(
                  logFileName,
                  this.GetSerilogLogLevel(),
                  "{ThreadId} {Timestamp:HH:mm:ss} {ScLevel} {Message}{NewLine}{Exception}",
                  fileSizeLimitBytes: fileSize,
                  rollOnFileSizeLimit: true), bufferSize: 500)
              .CreateLogger();

For clarity I’ve extracted the file path to a variable. It now includes the environment name and an exact time of the file to help better identify which file we need to look at. When the site runs the file name looks like SCF.HabitatAuthoring.2019-02-27-065419.log.txt.

Do be careful that your name provides enough uniqueness so that an existing log file won’t be overwritten. In this case, by including the time down to the second, even if the server restarted twice in a single minute, we wouldn’t accidentally overwrite the existing file. If you wanted to be super-paranoid, you could use epoch or something.

Thanks for reading. :-)