Search code examples
uwpmetrolog

Logging in Local time in Metrolog


My Metrolog output looks like its being logged in GMT. My timezone is GMT +5.30. The time is set correctly on the device. How can I make Metrolog to log in local time?

Example Log: 4|2017-05-15T05:05:36.6887812+00:00|TRACE|3|App|Analytics configured


Solution

  • You can change the trace layout by creating a class extending MetroLog.Layouts.Layout, in which you can display the DateTime according to your timezone :

    public class CustomLayout : MetroLog.Layouts.Layout
    {
        /// <summary>
        /// Create a formatted string based on given informations
        /// </summary>
        /// <param name="context"><see cref="LogWriteContext"/></param>
        /// <param name="info"><see cref="LogEventInfo"/></param>
        /// <returns>Formatted string to log</returns>
        public override string GetFormattedString(LogWriteContext context, LogEventInfo info)
        {
            return $"{info.SequenceID}|{info.TimeStamp.LocalDateTime}|{info.Level}|{info.Logger}|{info.Message}|{info.Exception}";
        }
    }
    

    And don't forget to use this custom layout when initializing your target. For instance, if you're using a DebugTarget, you should do something like :

    var loggingConfiguration = new LoggingConfiguration { IsEnabled = true };
    loggingConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new DebugTarget(new CustomLayout()));
    

    And then create your log manager :

    var logManager = LogManagerFactory.CreateLogManager(loggingConfiguration);