Logging CsvRequestLogger data to database

Hello @mythz ,

I have enabled the RequestLogger (CsvRequestLogger) feature and using the default settings I am able to see the csv file is being generated on the hard drive and logs are being recorded in the csv file, so far so good.

May I kindly request you to please guide me that how can I enhance the RequestLogger or use it in a way that I want to pick and choose specific columns data and store it in the log table in my postgres SQL database.
I want to store the columns values in the database which are available via the RequestLogger (CsvRequestLogger) which are mentioned below

Id,TraceId,OperationName,DateTime,StatusCode,StatusDescription,HttpMethod,AbsoluteUri,PathInfo,RequestBody,RequestDto,UserAuthId,SessionId,IpAddress,ForwardedFor,Referer,Headers,FormData,Items,ResponseHeaders,Session,ResponseDto,ErrorResponse,ExceptionSource,ExceptionData,RequestDuration,Meta

Appreciate your kind guidance with some code snippet.

Thanks

Here’s the implementation of CsvRequestLogger.

If you want to enhance it you should be able to create a subclass that performs the default implementation plus your own by either overriding WriteLogs or Log methods, e.g:

public class MyDbLog
{
    // Include all properties you want in DB Table    
}

public class MyRequestLogger : CsvRequestLogger
{
    public override void WriteLogs(List<RequestLogEntry> logs, string logFile)
    {
        using var db = HostContext.AppHost.GetDbConnection();
        var rows = logs.Map(x => x.ConvertTo<MyDbLog>());
        db.InsertAll(rows);
        
        base.WriteLogs(logs, logFile);
    }
}

You’ll need to create your RDBMS table using either db.CreateTable<T>() or in a OrmLite DB Migrations if you’re using it.

Thanks @mythz, I will follow your suggestion.

1 Like