DEV Community

Cover image for Serilog: Get the last log file
Karen Payne
Karen Payne

Posted on

Serilog: Get the last log file

Introduction

When working with Serilog writing to a log file configured with a rolling interval, Serilog does not expose the log file name. Learn how to obtain the last log file written to using FileSystemGlobbing.

Serilog configuration

The base path and file name are stored in appsettings.json under the section SerilogSection.

{
  "SerilogSection": {
    "FileName": "LogFiles/EF-Log.txt"
  }
}
Enter fullscreen mode Exit fullscreen mode

Model

public class SerilogSection
{
    public string FileName { get; set; }
    public string Folder => Path.GetDirectoryName(FileName);
}
Enter fullscreen mode Exit fullscreen mode

Class to configure Serilog, which creates a new file every minute for demonstration rather than one log per day.

internal class SetupLogging
{
    public static void Development()
    {
        var fileName = ConfigurationHelpers.GetSerilogFileName();

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()

            .WriteTo.File(fileName,
                rollingInterval: RollingInterval.Minute,
                outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}")
            .CreateLogger();

    }
}
Enter fullscreen mode Exit fullscreen mode

Class to read settings from appsettings.json

public static class ConfigurationHelpers
{

    public static SerilogSection GetSerilogSection()
    {
        IConfiguration config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        var section = new SerilogSection();
        config.GetSection("SerilogSection").Bind(section);
        return section;
    }

    public static string GetSerilogFileName() => GetSerilogSection().FileName;
    public static string GetSerilogFolder() => GetSerilogSection().Folder;
}
Enter fullscreen mode Exit fullscreen mode

Get last log file

Class to get the last log file.

Uses FileSystemGlobbing

public static class FileHelper
{

    public static FileInfo? GetLogFileName()
    {
        var rootPath = ConfigurationHelpers.GetSerilogFolder();

        // could be .log or .json depending on configuration
        var pattern = "**/*.txt";


        if (!Directory.Exists(rootPath)) throw new DirectoryNotFoundException(rootPath);

        var matcher = new Matcher();
        matcher.AddInclude(pattern);

        var directoryInfo = new DirectoryInfo(rootPath);
        var dirWrapper = new DirectoryInfoWrapper(directoryInfo);

        var matchResult = matcher.Execute(dirWrapper);

        var newest = matchResult.Files
            .Select(f => new FileInfo(Path.Combine(rootPath, f.Path)))
            .OrderByDescending(f => f.LastWriteTimeUtc)
            .FirstOrDefault();

        return newest;
    }
}
Enter fullscreen mode Exit fullscreen mode

Use the following to get the full path and file name.

FileHelper.GetLogFileName()!.FullName
Enter fullscreen mode Exit fullscreen mode

Summary

Using the provided code, a developer can easily retrieve the last log file written to.

Source code

Sample code

Uses EF Core and an interceptor to log changes to a record in a local dB database. Before running, open Scripts\populate.sql and follow the instructions.

Top comments (0)