首页 > 解决方案 > 从 Lambda 函数调用方法时,Serilog 记录器未记录

问题描述

我正在使用 serilog 进行日志记录。我在一个项目中有一个 AWS lambda 函数,它将数据记录到 cloudwatch group lambda_logs。我oflline_method()在另一个项目中也有一个方法,默认情况下将数据记录到 cloudwatch group offline_logsoflline_method()在某些情况下,lambda 在内部调用方法。在这种情况下,所有与 lambda 相关的日志都需要登录到lambda_logsgroup 中,而与 lambda 相关的日志offline_method需要登录到offline_logs. 但是offline_method只有当它被 lambda 调用时,写入的日志才不会登录到 cloudwatch 组。

namespace Online
{
    public class lambda
    {
        public async Task<KinesisFirehoseResponse> MethodA(ILambdaContext context)
        {
            //this will be logged into lambda_logs
            context.Logger.LogLine("Logged by the method MethodA in lambda");

            var firehoseResponse = new KinesisFirehoseResponse();

            //Calls the oflline_method from offline project 
            var a = oflline_method();

            return firehoseResponse;
        }
    }
}


namespace OfflineProject
{
    public class Offline
    {
        private readonly ILogger<Offline> _logger;

        public Offline()
        {
            _logger = new SerilogLoggerFactory().CreateLogger<Offline>();
        }

        public string oflline_method()
        {
            //this should be logged into offline_logs, but it is not happening only when called by lambda
            _logger.LogInformation(" Logged by the method oflline_method in offline");

            return "from offline";

        }
    }
}

依赖注入用于创建记录器对象。下面是 Startup.cs 中的配置

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    var options = new CloudWatchSinkOptions
    {
        LogGroupName = "offline_logs",
        TextFormatter = new LogFormatter(),
        MinimumLogEventLevel = LogEventLevel.Verbose,
        BatchSizeLimit = 100,
        QueueSizeLimit = 10000,
        Period = TimeSpan.FromSeconds(10),
        CreateLogGroup = true,
        LogStreamNameProvider = new AwsCloudWatchLogStream(),
        RetryAttempts = 5
    };

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.ControlledBy(new EnvironmentVariableLoggingLevelSwitch(DebugMode))
        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
        .MinimumLevel.Override("System", LogEventLevel.Warning)
        .WriteTo.AmazonCloudWatch(options, new AmazonCloudWatchLogsClient())
        .CreateLogger();
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
}

标签: c#.net-coreaws-lambdaserilog

解决方案


推荐阅读