@@ -515,3 +515,95 @@ Below are some output examples for different casing.
515515 "function_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72"
516516 }
517517 ```
518+
519+ ## Custom Log formatter (Bring Your Own Formatter)
520+
521+ You can customize the structure (keys and values) of your log entries by implementing a custom log formatter and override default log formatter using `` Logger.UseFormatter `` method. You can implement a custom log formatter by inheriting the `` ILogFormatter `` class and implementing the `` object FormatLogEntry(LogEntry logEntry) `` method.
522+
523+ === "Function.cs"
524+
525+ ```c# hl_lines="11"
526+ /**
527+ * Handler for requests to Lambda function.
528+ */
529+ public class Function
530+ {
531+ /// <summary>
532+ /// Function constructor
533+ /// </summary>
534+ public Function()
535+ {
536+ Logger.UseFormatter(new CustomLogFormatter());
537+ }
538+
539+ [Logging(CorrelationIdPath = "/headers/my_request_id_header", SamplingRate = 0.7)]
540+ public async Task<APIGatewayProxyResponse> FunctionHandler
541+ (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
542+ {
543+ ...
544+ }
545+ }
546+ ```
547+ === "CustomLogFormatter.cs"
548+
549+ ```c#
550+ public class CustomLogFormatter : ILogFormatter
551+ {
552+ public object FormatLogEntry(LogEntry logEntry)
553+ {
554+ return new
555+ {
556+ Message = logEntry.Message,
557+ Service = logEntry.Service,
558+ CorrelationIds = new
559+ {
560+ AwsRequestId = logEntry.LambdaContext?.AwsRequestId,
561+ XRayTraceId = logEntry.XRayTraceId,
562+ CorrelationId = logEntry.CorrelationId
563+ },
564+ LambdaFunction = new
565+ {
566+ Name = logEntry.LambdaContext?.FunctionName,
567+ Arn = logEntry.LambdaContext?.InvokedFunctionArn,
568+ MemoryLimitInMB = logEntry.LambdaContext?.MemoryLimitInMB,
569+ Version = logEntry.LambdaContext?.FunctionVersion,
570+ ColdStart = logEntry.ColdStart,
571+ },
572+ Level = logEntry.Level.ToString(),
573+ Timestamp = logEntry.Timestamp.ToString("o"),
574+ Logger = new
575+ {
576+ Name = logEntry.Name,
577+ SampleRate = logEntry.SamplingRate
578+ },
579+ };
580+ }
581+ }
582+ ```
583+
584+ === "Example CloudWatch Logs excerpt"
585+
586+ ```json
587+ {
588+ "Message": "Test Message",
589+ "Service": "lambda-example",
590+ "CorrelationIds": {
591+ "AwsRequestId": "52fdfc07-2182-154f-163f-5f0f9a621d72",
592+ "XRayTraceId": "1-61b7add4-66532bb81441e1b060389429",
593+ "CorrelationId": "correlation_id_value"
594+ },
595+ "LambdaFunction": {
596+ "Name": "test",
597+ "Arn": "arn:aws:lambda:eu-west-1:12345678910:function:test",
598+ "MemorySize": 128,
599+ "Version": "$LATEST",
600+ "ColdStart": true
601+ },
602+ "Level": "Information",
603+ "Timestamp": "2021-12-13T20:32:22.5774262Z",
604+ "Logger": {
605+ "Name": "AWS.Lambda.Powertools.Logging.Logger",
606+ "SampleRate": 0.7
607+ }
608+ }
609+ ```
0 commit comments