从Lambda函数调用方法时,Serilog记录器未记录

时间:2020-07-14 07:30:46

标签: c# .net-core aws-lambda serilog

我正在使用serilog进行日志记录。我在一个项目中有一个AWS lambda函数,该函数会将数据记录到cloudwatch组lambda_logs中。我在另一个项目中也有方法oflline_method(),默认情况下,该方法会将数据记录到云监视组offline_logs中。在某些情况下,lambda在内部调用oflline_method()方法。在这种情况下,需要将所有与lambda相关的日志记录到lambda_logs组中,而将与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));
}

0 个答案:

没有答案