-
Notifications
You must be signed in to change notification settings - Fork 151
NLog cloud logging with Azure function or AWS lambda
Standard log files doesn't always work well in the cloud. It can be difficult to access the log files after the function / lambda has completed.
The easy solution is to perform logging to these locations:
- Console - NLog ConsoleTarget
- System.Diagnostic.Trace - NLog TraceTarget (
rawWrite="true"
) - TextWriter / Stream - NLog TextWriterTarget
Then update the configuration for the function / lambda to perform capture of the output and save it to cloud storage. The execution of the function / lambda will then not be bothered with any network issues to the cloud storage.
The NLog JsonLayout can then be configured to enable structured logging.
var lambdaLogger = lambaContext.Logger;
var loggerTarget = new NLog.Targets.MethodCallTarget("MyTarget", (logEvent,parms) => lambdaLogger.LogLine(parms[0].ToString()));
loggerTarget.Parameters.Add(new NLog.Targets.MethodCallParameter("${message"});
var nlogConfig = new NLog.Config.LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(loggerTarget);
NLog.LogManager.Configuration = nlogConfig;
var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
nlogLogger.Info("Hello World");
MicrosoftILoggerTarget can help:
var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
var nlogConfig = new NLog.Config.LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(loggerTarget);
NLog.LogManager.Configuration = nlogConfig;
var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
nlogLogger.Info("Hello World");
It is possible for the lambda / function to write directly to the cloud storage, but it might be more fragile. The cloud usually has high latency so the execution might be affected by timeouts/retries etc. Make sure to use the matching region of the cloud storage. Very important to flush before exit.
See the different NLog Integrations (Cloud)