delphimvcframework
delphimvcframework copied to clipboard
Get TWebContext in a CustomLogger
How can I use TWebContext within a CustomLogger to obtain Customer data in an ISAPI application?
I tried to use a TWebContext Helper, but I don't have access to uWebModule.
procedure LogRow(const LogItem: TLogItem; out LogRow: string);
const
LOG_FORMAT = '%0:s [%1:-8s] [%2:s] [%3:s] %4:s [%5:s]';
var
fFormatSettings: TFormatSettings;
begin
fFormatSettings := LoggerPro.GetDefaultFormatSettings;
LogRow := Format(LOG_FORMAT,[datetimetostr(LogItem.TimeStamp, fFormatSettings), LogItem.LogTypeAsString, getContext1, getContext2, LogItem.LogMessage, LogItem.LogTag]);
end;
function GetLogger: ILogWriter;
var
FileOptions: TFileAppenderOptions;
FileAppend: TLoggerProFileAppender;
begin
FileAppend := TLoggerProFileAppender.Create(5, 2000, 'Logs', FileOptions, '%s.%2.2d.log');
FileAppend.OnLogRow := FileRow;
Result := BuildLogWriter([FileAppend, TLoggerProOutputDebugStringAppender.Create], nil, TLogType.Debug);
end;
You have access to TWebContext within a method of your controller. You can extract the information from TWebContext and pass it to LogWriter.
var
lLogInfo: string;
begin
lLogInfo := 'path: ' + Context.Request.PathInfo + ' - client_ip: ' + Context.Request.ClientIp;
Log.Info(LLogInfo, 'logtag');
Or if you want to log all requests you can create middleware that intercepts the request and takes the customer's information. See https://github.com/danieleteti/delphimvcframework/tree/master/samples/middleware_analytics
I chose to change the log by overriding the OnRouterLog procedure in WebModule and still use CustomLogger as in the example samples\customlogger.
In addition, I saw the need to change the CustomExceptionHandling procedure by turning it into a handler, this allows me to also change the output log if I use the WebModuleException.
Please check the Pull Request with the modifications #478