.netenterprise-librarylogging-application-block

Logging application block : database trace listener timestamp


I'm logging exception using Microsoft Enterprise Library Logging Application Block. I'm using the database trace listener.

Timestamp of the log entry is in UTC time by default.

I know I can have the timestamp of local time in the 'FormattedMessage' column of the 'Log' table by setting the log formatter like this : Timestamp: {timestamp(local)}

How can I do the same thing with the 'Timestamp' column ?

Thank you.


Solution

  • The easiest way to do what you want is to set the Timestamp property of the LogEntry.

    E.g.:

    LogEntry le = new LogEntry()
    {
        Message = "Log it",
        TimeStamp = DateTime.Now // use local time
    };
    
    le.Categories.Add("General");
    
    Logger.Write(le);
    

    Other options to do what you want would be to create a Custom Trace Listener or to modify the WriteLog stored procedure to use any value you wish. You could simply use GETDATE() or you could do some manipulation of the passed in UTC Timestamp:

    DATEADD(HOUR, DATEDIFF(HOUR, GETUTCDATE(), GETDATE()), timestamp) 
    

    As a point of interest (since you wouldn't normally use this type of code), if you use the Write() method of the FormattedDatabaseTraceListener directly it uses the local DateTime. E.g.:

    var dbWriter = new FormattedDatabaseTraceListener(
        EnterpriseLibraryContainer.Current.GetInstance<Database>(),
        "writeLog", "AddCategory", new TextFormatter());
    
    dbWriter.Write("Log this!", "General");
    

    But as a commenter wrote, I would recommend sticking with UTC.