示例#1
0
        /// <inheritdoc/>
        protected override void InitializeTarget()
        {
            if (_core != null)
            {
                _core.Close();
                _core = null;
            }

            var config = new AWSLoggerConfig(RenderSimpleLayout(LogGroup, nameof(LogGroup)))
            {
                DisableLogGroupCreation = DisableLogGroupCreation,
                Region              = RenderSimpleLayout(Region, nameof(Region)),
                ServiceUrl          = RenderSimpleLayout(ServiceUrl, nameof(ServiceUrl)),
                Credentials         = Credentials,
                Profile             = RenderSimpleLayout(Profile, nameof(Profile)),
                ProfilesLocation    = RenderSimpleLayout(ProfilesLocation, nameof(ProfilesLocation)),
                BatchPushInterval   = BatchPushInterval,
                BatchSizeInBytes    = BatchSizeInBytes,
                MaxQueuedMessages   = MaxQueuedMessages,
                LogStreamNameSuffix = RenderSimpleLayout(LogStreamNameSuffix, nameof(LogStreamNameSuffix)),
                LogStreamNamePrefix = RenderSimpleLayout(LogStreamNamePrefix, nameof(LogStreamNamePrefix)),
                LibraryLogErrors    = LibraryLogErrors,
                LibraryLogFileName  = LibraryLogFileName,
                FlushTimeout        = FlushTimeout
            };

            _core = new AWSLoggerCore(config, "NLog");
            _core.LogLibraryAlert += AwsLogLibraryAlert;
        }
示例#2
0
        public static void Handle(bool isProduction, ILoggingBuilder builder, string awsLogGroupName)
        {
            builder.ClearProviders();

            if (!isProduction)
            {
                builder.AddConsole();
            }

            if (string.IsNullOrEmpty(awsLogGroupName))
            {
                return;
            }

            using var cloudwatchLogsClient = new AmazonCloudWatchLogsClient();

            bool logGroupExists = LogGroupExists(cloudwatchLogsClient, awsLogGroupName);

            if (!logGroupExists)
            {
                int days = isProduction ? 30 : 1;
                CreateLogGroup(cloudwatchLogsClient, awsLogGroupName, days);
            }

            var awsLoggerConfig = new AWSLoggerConfig
            {
                LogGroup                = awsLogGroupName,
                BatchPushInterval       = isProduction ? TimeSpan.FromMinutes(1) : TimeSpan.FromSeconds(2),
                DisableLogGroupCreation = true,
                LogStreamNamePrefix     = string.Empty
            };

            builder.AddAWSProvider(awsLoggerConfig, LogLevel.Information);
            Console.WriteLine($"Will write logs to: {awsLogGroupName}");
        }
        /// <summary>
        /// Construct an instance of AWSLoggerCore
        /// </summary>
        /// <param name="config">Configuration options for logging messages to AWS</param>
        /// <param name="logType">Logging Provider Name to include in UserAgentHeader</param>
        public AWSLoggerCore(AWSLoggerConfig config, string logType)
        {
            _config = config;
            _logType = logType;

            var credentials = DetermineCredentials(config);

            if (!string.IsNullOrWhiteSpace(_config.ServiceUrl))
            {
                var cloudWatchConfig = new AmazonCloudWatchLogsConfig
                {
                    ServiceURL = _config.ServiceUrl
                };

                _client = new AmazonCloudWatchLogsClient(credentials, cloudWatchConfig);
            }
            else if (_config.Region != null)
            {
                _client = new AmazonCloudWatchLogsClient(credentials, Amazon.RegionEndpoint.GetBySystemName(_config.Region));
            }
            else
            {
                _client = new AmazonCloudWatchLogsClient(credentials);
            }

            ((AmazonCloudWatchLogsClient)this._client).BeforeRequestEvent += ServiceClientBeforeRequestEvent;
            ((AmazonCloudWatchLogsClient)this._client).ExceptionEvent += ServiceClienExceptionEvent;

            StartMonitor();
            RegisterShutdownHook();
        }
示例#4
0
        /// <summary>
        /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
        /// <param name="filter">A filter function that has the logger category name and log level which can be used to filter messages being sent to AWS.</param>
        /// <returns></returns>
        public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfig config, Func <string, LogLevel, bool> filter)
        {
            var provider = new AWSLoggerProvider(config, filter);

            builder.AddProvider(provider);
            return(builder);
        }
示例#5
0
        /// <summary>
        /// Construct an instance of AWSLoggerCore
        /// </summary>
        /// <param name="config">Configuration options for logging messages to AWS</param>
        /// <param name="logType">Logging Provider Name to include in UserAgentHeader</param>
        public AWSLoggerCore(AWSLoggerConfig config, string logType)
        {
            _config  = config;
            _logType = logType;

            var awsConfig = new AmazonCloudWatchLogsConfig();

            if (!string.IsNullOrWhiteSpace(_config.ServiceUrl))
            {
                var serviceUrl = _config.ServiceUrl.Trim();
                awsConfig.ServiceURL = serviceUrl;
                if (serviceUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                {
                    awsConfig.UseHttp = true;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(_config.Region))
                {
                    awsConfig.RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(_config.Region);
                }
            }

            var credentials = DetermineCredentials(config);

            _client = new AmazonCloudWatchLogsClient(credentials, awsConfig);


            ((AmazonCloudWatchLogsClient)this._client).BeforeRequestEvent += ServiceClientBeforeRequestEvent;
            ((AmazonCloudWatchLogsClient)this._client).ExceptionEvent     += ServiceClienExceptionEvent;

            StartMonitor();
            RegisterShutdownHook();
        }
示例#6
0
        /// <summary>
        /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
        /// <param name="minLevel">The minimum log level for messages to be written.</param>
        /// <returns></returns>
        public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfig config, LogLevel minLevel)
        {
            var provider = new AWSLoggerProvider(config, minLevel);

            factory.AddProvider(provider);
            return(factory);
        }
示例#7
0
        /// <summary>
        /// Initialize the appender based on the options set.
        /// </summary>
        public override void ActivateOptions()
        {
            if (_core != null)
            {
                _core.Close();
                _core = null;
            }

            var config = new AWSLoggerConfig(this.LogGroup)
            {
                DisableLogGroupCreation = DisableLogGroupCreation,
                Region              = Region,
                ServiceUrl          = ServiceUrl,
                Credentials         = Credentials,
                Profile             = Profile,
                ProfilesLocation    = ProfilesLocation,
                BatchPushInterval   = BatchPushInterval,
                BatchSizeInBytes    = BatchSizeInBytes,
                MaxQueuedMessages   = MaxQueuedMessages,
                LogStreamNameSuffix = LogStreamNameSuffix,
                LogStreamNamePrefix = LogStreamNamePrefix,
                LibraryLogErrors    = LibraryLogErrors,
                LibraryLogFileName  = LibraryLogFileName
            };

            _core = new AWSLoggerCore(config, "Log4net");
        }
示例#8
0
        /// <summary>
        /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
        /// <param name="filter">A filter function that has the logger category name and log level which can be used to filter messages being sent to AWS.</param>
        /// <returns></returns>
        public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfig config, Func <string, LogLevel, bool> filter)
        {
            var provider = new AWSLoggerProvider(config, filter);

            factory.AddProvider(provider);
            return(factory);
        }
示例#9
0
 /// <summary>
 /// Creates the logging provider with the configuration information to connect to AWS and how the messages should be sent.
 /// </summary>
 /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
 /// <param name="filter">A filter function that has the logger category name and log level which can be used to filter messages being sent to AWS.</param>
 /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param>
 public AWSLoggerProvider(AWSLoggerConfig config, Func <string, LogLevel, bool> filter, Func <LogLevel, object, Exception, string> formatter = null)
 {
     _scopeProvider   = NullExternalScopeProvider.Instance;
     _core            = new AWSLoggerCore(config, "ILogger");
     _customFilter    = filter;
     _customFormatter = formatter;
 }
示例#10
0
        /// <summary>
        /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
        /// <param name="minLevel">The minimum log level for messages to be written.</param>
        /// <returns></returns>
        public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfig config, LogLevel minLevel)
        {
            var provider = new AWSLoggerProvider(config, minLevel);

            builder.AddProvider(provider);
            return(builder);
        }
示例#11
0
        /// <summary>
        /// AWSSeriLogger target that is called when the customer is using
        /// Serilog.Settings.Configuration to set the SeriLogger configuration
        /// using a Json input.
        /// </summary>
        public static LoggerConfiguration AWSSeriLog(
            this LoggerSinkConfiguration loggerConfiguration,
            IConfiguration configuration,
            IFormatProvider iFormatProvider = null,
            ITextFormatter textFormatter    = null)
        {
            AWSLoggerConfig config = new AWSLoggerConfig();

            config.LogGroup = configuration[LOG_GROUP];
            if (configuration[DISABLE_LOG_GROUP_CREATION] != null)
            {
                config.DisableLogGroupCreation = bool.Parse(configuration[DISABLE_LOG_GROUP_CREATION]);
            }
            if (configuration[REGION] != null)
            {
                config.Region = configuration[REGION];
            }
            if (configuration[SERVICEURL] != null)
            {
                config.ServiceUrl = configuration[SERVICEURL];
            }
            if (configuration[PROFILE] != null)
            {
                config.Profile = configuration[PROFILE];
            }
            if (configuration[PROFILE_LOCATION] != null)
            {
                config.ProfilesLocation = configuration[PROFILE_LOCATION];
            }
            if (configuration[BATCH_PUSH_INTERVAL] != null)
            {
                config.BatchPushInterval = TimeSpan.FromMilliseconds(Int32.Parse(configuration[BATCH_PUSH_INTERVAL]));
            }
            if (configuration[BATCH_PUSH_SIZE_IN_BYTES] != null)
            {
                config.BatchSizeInBytes = Int32.Parse(configuration[BATCH_PUSH_SIZE_IN_BYTES]);
            }
            if (configuration[MAX_QUEUED_MESSAGES] != null)
            {
                config.MaxQueuedMessages = Int32.Parse(configuration[MAX_QUEUED_MESSAGES]);
            }
            if (configuration[LOG_STREAM_NAME_SUFFIX] != null)
            {
                config.LogStreamNameSuffix = configuration[LOG_STREAM_NAME_SUFFIX];
            }
            if (configuration[LOG_STREAM_NAME_PREFIX] != null)
            {
                config.LogStreamNamePrefix = configuration[LOG_STREAM_NAME_PREFIX];
            }
            if (configuration[LIBRARY_LOG_FILE_NAME] != null)
            {
                config.LibraryLogFileName = configuration[LIBRARY_LOG_FILE_NAME];
            }
            if (configuration[LIBRARY_LOG_ERRORS] != null)
            {
                config.LibraryLogErrors = Boolean.Parse(configuration[LIBRARY_LOG_ERRORS]);
            }
            return(AWSSeriLog(loggerConfiguration, config, iFormatProvider, textFormatter));
        }
示例#12
0
 /// <summary>
 /// AWSSeriLogger target that is called when the customer
 /// explicitly creates a configuration of type AWSLoggerConfig
 /// to set the SeriLogger configuration.
 /// </summary>
 public static LoggerConfiguration AWSSeriLog(
     this LoggerSinkConfiguration loggerConfiguration,
     AWSLoggerConfig configuration   = null,
     IFormatProvider iFormatProvider = null,
     ITextFormatter textFormatter    = null)
 {
     return(loggerConfiguration.Sink(new AWSSink(configuration, iFormatProvider, textFormatter)));
 }
 /// <summary>
 /// AWSSeriLogger target that is called when the customer
 /// explicitly creates a configuration of type AWSLoggerConfig
 /// to set the SeriLogger configuration.
 /// </summary>
 public static LoggerConfiguration AWSSeriLog(
     this LoggerSinkConfiguration loggerConfiguration,
     AWSLoggerConfig configuration          = null,
     IFormatProvider iFormatProvider        = null,
     ITextFormatter textFormatter           = null,
     LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose)
 {
     return(loggerConfiguration.Sink(new AWSSink(configuration, iFormatProvider, textFormatter), restrictedToMinimumLevel));
 }
示例#14
0
        static async Task Main(string[] args)
        {
            RegionEndpoint awsRegion = RegionEndpoint.EUWest1;

            AWSLoggerConfig loggerConfig = new AWSLoggerConfig()
            {
                Region   = awsRegion.SystemName,
                LogGroup = "CutieBotLogs"
            };

            var host = new HostBuilder()
                       .ConfigureServices((context, services) =>
            {
                services.AddLogging();

                // Add infrastructure and clients
                services.AddSingleton <AmazonCloudWatchClient>(new AmazonCloudWatchClient(awsRegion));
                services.AddSingleton <AmazonSQSClient>(new AmazonSQSClient(awsRegion));
                services.AddSingleton <AmazonDynamoDBClient>(new AmazonDynamoDBClient(awsRegion));
                services.AddSingleton <AmazonComprehendClient>(new AmazonComprehendClient(awsRegion));
                services.AddSingleton <CloudWatchMetrics>();
                services.AddSingleton <MessageRepository>();
                services.AddSingleton <MemberRepository>();
                services.AddSingleton <DiscordClient>(new DiscordClient(new DiscordConfiguration
                {
                    Token     = (string)Environment.GetEnvironmentVariables()["DISCORD_TOKEN"],
                    TokenType = TokenType.Bot,
                    LogLevel  = DSharpPlus.LogLevel.Debug
                }));

                // Add message processors
                services.AddSingleton <IMessageProcessor, GalleryMessageProcessor>();
                services.AddSingleton <IMessageProcessor, ImageMessageProcessor>();
                services.AddSingleton <IMessageProcessor, MessageCountProcessor>();
                services.AddSingleton <IMessageProcessor, MessageCountInfoProcessor>();
                services.AddSingleton <IMessageProcessor, SentimentMessageProcessor>();
                services.AddSingleton <IMessageProcessor, ShowSentimentMessageProcessor>();
                services.AddSingleton <MessageDispatcher>();

                // Add services
                services.AddHostedService <DiscordClientService>();
                services.AddHostedService <SqsListenerService>();
            })
                       .ConfigureLogging((context, logger) =>
            {
                logger.AddProvider(new AWSLoggerProvider(loggerConfig));
                logger.AddConsole();
            })
                       .Build();

            using (host)
            {
                await host.StartAsync();

                await host.WaitForShutdownAsync();
            }
        }
 private static AWSCredentials LookupCredentialsFromProfileStore(AWSLoggerConfig config)
 {
     var credentialProfileStore = string.IsNullOrEmpty(config.ProfilesLocation)
         ? new CredentialProfileStoreChain()
         : new CredentialProfileStoreChain(config.ProfilesLocation);
     if (credentialProfileStore.TryGetAWSCredentials(config.Profile, out var credentials))
         return credentials;
     else
         return null;
 }
        public AWSLoggerCore(IAmazonCloudWatchLogs client, AWSLoggerConfig config, string logType)
        {
            _config  = config;
            _logType = logType;
            _client  = client;

            ((AmazonCloudWatchLogsClient)this._client).BeforeRequestEvent += ServiceClientBeforeRequestEvent;

            StartMonitor();
            RegisterShutdownHook();
        }
示例#17
0
        public async Task TestCoreWithDisableLogGroupCreation()
        {
            var logGroupName = nameof(TestCoreWithDisableLogGroupCreation);

            using (var client = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest2))
            {
                var config = new AWSLoggerConfig(logGroupName)
                {
                    Region = RegionEndpoint.USWest2.SystemName,
                    DisableLogGroupCreation = true,
                };

                var resourceNotFoundPromise = new TaskCompletionSource <bool>();  // true means we saw expected exception; false otherwise
                var core = new AWSLoggerCore(config, "unit");
                core.LogLibraryAlert += (sender, e) =>
                {
                    if (e.Exception is ResourceNotFoundException)
                    {
                        // saw EXPECTED exception.
                        resourceNotFoundPromise.TrySetResult(true);
                    }
                    else if (e.Exception != null)
                    {
                        _output.WriteLine("Was not expecting to see exception: {0} @{1}", e.Exception, e.ServiceUrl);
                    }
                };

                var tsk = Task.Factory.StartNew(() =>
                {
                    core.AddMessage("Test message added at " + DateTimeOffset.UtcNow.ToString());
                    core.Flush();
                });

                await Task.WhenAny(tsk, resourceNotFoundPromise.Task).ConfigureAwait(false);

                resourceNotFoundPromise.TrySetResult(false);
                Assert.True(await resourceNotFoundPromise.Task);

                // now we create the log group, late.
                await client.CreateLogGroupAsync(new CreateLogGroupRequest
                {
                    LogGroupName = logGroupName
                });

                _testFixure.LogGroupNameList.Add(logGroupName);

                // wait for the flusher task to finish, which should actually proceed OK, now that we've created the expected log group.
                await tsk.ConfigureAwait(false);

                core.Close();
            }
        }
        private static AWSCredentials DetermineCredentials(AWSLoggerConfig config)
        {
            if (config.Credentials != null)
            {
                return(config.Credentials);
            }
            if (!string.IsNullOrEmpty(config.Profile) && StoredProfileAWSCredentials.IsProfileKnown(config.Profile, config.ProfilesLocation))
            {
                return(new StoredProfileAWSCredentials(config.Profile, config.ProfilesLocation));
            }

            return(FallbackCredentialsFactory.GetCredentials());
        }
示例#19
0
 private static AWSCredentials DetermineCredentials(AWSLoggerConfig config)
 {
     if (config.Credentials != null)
     {
         return(config.Credentials);
     }
     if (!string.IsNullOrEmpty(config.Profile) && new CredentialProfileStoreChain(config.ProfilesLocation)
         .TryGetAWSCredentials(config.Profile, out var credentials))
     {
         return(credentials);
     }
     return(FallbackCredentialsFactory.GetCredentials());
 }
示例#20
0
        public void OnGet()
        {
            _logger.LogCritical("Critical");
            _logger.LogError("Error");
            _logger.LogWarning("Warning");
            _logger.LogInformation("Information");
            _logger.LogDebug("Debug");
            _logger.LogTrace("Trace");

            _logger.LogInformation("Welcome to the AWS Logger. You are viewing the home page");
            LatestErrorLogs  = AWSLoggerConfig.GetLatestErrorLogs();
            LogLibraryErrors = AWSLoggerConfig.GetLogLibraryErrors();
        }
        static void Main(string[] args)
        {
            AWSLoggerConfig configuration = new AWSLoggerConfig("Serilog.ConfigExample")
            {
                Region = "us-east-1"
            };

            var logger = new LoggerConfiguration()
                         .WriteTo.AWSSeriLog(configuration)
                         .CreateLogger();

            logger.Information("Hello!");
        }
 private static AWSCredentials DetermineCredentials(AWSLoggerConfig config)
 {
     if (config.Credentials != null)
     {
         return config.Credentials;
     }
     if (!string.IsNullOrEmpty(config.Profile))
     {
         var credentials = LookupCredentialsFromProfileStore(config);
         if (credentials != null)
             return credentials;
     }
     return FallbackCredentialsFactory.GetCredentials();
 }
        public void DefaultConfig()
        {
            var config = new AWSLoggerConfig
            {
            };
            var streamName = AWSLoggerCore.GenerateStreamName(config);

            var tokens = SplitStreamName(streamName);

            Assert.Equal(2, tokens.Length);

            Assert.True(IsTokenDate(tokens[0]));
            Assert.True(IsTokenGuid(tokens[1]));
        }
        public void SuffixSet()
        {
            var config = new AWSLoggerConfig
            {
                LogStreamNameSuffix = "TheSuffix"
            };
            var streamName = AWSLoggerCore.GenerateStreamName(config);

            var tokens = SplitStreamName(streamName);

            Assert.Equal(2, tokens.Length);

            Assert.True(IsTokenDate(tokens[0]));
            Assert.Equal(config.LogStreamNameSuffix, tokens[1]);
        }
示例#25
0
        /// <summary>
        /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
        /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param>
        /// <returns></returns>
        public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfig config, Func <LogLevel, object, Exception, string> formatter = null)
        {
            // If config is null. Assuming the logger is being activated in a debug environment
            // and skip adding the provider. We don't want to prevent developers running their application
            // locally because they don't have access or want to use AWS for their local development.
            if (config == null)
            {
                return(builder);
            }

            var provider = new AWSLoggerProvider(config, formatter);

            builder.AddProvider(provider);
            return(builder);
        }
示例#26
0
 private void LogLibraryServiceError(Exception ex, string serviceUrl = null)
 {
     LogLibraryAlert?.Invoke(this, new LogLibraryEventArgs(ex)
     {
         ServiceUrl = serviceUrl ?? GetServiceUrl()
     });
     try
     {
         AWSLoggerConfig.LogLibraryError(ex.Message + Environment.NewLine + "StackTrace: " + ex.StackTrace);
     }
     catch (Exception e)
     {
         Console.WriteLine("Exception caught when writing error log to file" + e.ToString());
     }
 }
示例#27
0
        /// <summary>
        /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param>
        /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param>
        /// <returns></returns>
        public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfig config, Func <LogLevel, object, Exception, string> formatter = null)
        {
            // If config is null. Assuming the logger is being activated in a debug environment
            // and skip adding the provider. We don't want to prevent developers running their application
            // locally because they don't have access or want to use AWS for their local development.
            if (config == null)
            {
                factory.CreateLogger("AWS.Logging.AspNetCore").LogWarning("AWSLoggerConfig is null, skipping adding AWS Logging provider.");
                return(factory);
            }

            var provider = new AWSLoggerProvider(config, formatter);

            factory.AddProvider(provider);
            return(factory);
        }
示例#28
0
        private void Configure(ILoggerFactory factory, LogLevel currentLevel)
        {
#if DEBUG
            bool logDirect = true;
#else
            bool logDirect    = false;
            var  logDirectStr = Environment.GetEnvironmentVariable("LOGGING_CLOUDWATCH");
            if (!string.IsNullOrEmpty(logDirectStr) && int.TryParse(logDirectStr, out var logDirectVal) && logDirectVal > 0)
            {
                logDirect = true;
            }
#endif
            if (logDirect)
            {
                var config = new AWSLoggerConfig()
                {
                    LibraryLogFileName = Path.Combine(Path.GetTempPath(), "aws-logger-errors.txt")
                };

                var group = Environment.GetEnvironmentVariable("LOGGING_CLOUDWATCH_GROUP");
#if DEBUG
                config.LogGroup = "SuperNova/default/debug";
#else
                config.LogGroup = string.IsNullOrEmpty(group) ? "SuperNova/default" : group;
#endif

                var batchPushSecsStr = Environment.GetEnvironmentVariable("LOGGING_CLOUDWATCH_BATCHPUSHSECS");
                if (!string.IsNullOrEmpty(batchPushSecsStr) && int.TryParse(batchPushSecsStr, out var batchPushSecs) && batchPushSecs > 0)
                {
                    config.BatchPushInterval = new TimeSpan(0, 0, batchPushSecs);
                }

                var batchPushBytesStr = Environment.GetEnvironmentVariable("LOGGING_CLOUDWATCH_BATCHPUSHBYTES");
                if (!string.IsNullOrEmpty(batchPushBytesStr) && int.TryParse(batchPushBytesStr, out var batchPushBytes) && batchPushBytes > 0)
                {
                    config.BatchSizeInBytes = batchPushBytes;
                }
                _factory.AddAWSProvider(config, currentLevel);
            }
            else
            {
                _factory.AddLambdaLogger(new LambdaLoggerOptions
                {
                    Filter = (s, logLevel) => logLevel >= currentLevel
                });
            }
        }
示例#29
0
        public static void Main(string[] args)
        {
            var configuration = new AWSLoggerConfig
            {
                Credentials             = CredentialsCarlos,
                Region                  = "us-east-1",
                LogGroup                = "hackaiti",
                DisableLogGroupCreation = true
            };

            Log.Logger = new LoggerConfiguration()
#if DEBUG
                         .MinimumLevel.Verbose()
#else
                         .MinimumLevel.Information()
#endif
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         //.Enrich.FromLogContext()
                         .Enrich.With(new LogsEnricher())
                         .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
                                                      .WithIgnoreStackTraceAndTargetSiteExceptionFilter()
                                                      .WithDefaultDestructurers()
                                                      .WithRootName("data"))
#if DEBUG
                         .WriteTo.Console(new LogsJsonFormatter())
                         //.WriteTo.AWSSeriLog(configuration, null, new LogsJsonFormatter())
#else
                         .WriteTo.AWSSeriLog(configuration, null, new LogsJsonFormatter())
#endif
                         .CreateLogger();

            try
            {
                Log.Information("starting web host");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "web host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
示例#30
0
        public void TestCoreWithoutDisableLogGroupCreation()
        {
            var logGroupName = nameof(TestCoreWithoutDisableLogGroupCreation) + DateTime.UtcNow.Ticks; // this one will have to be auto-created.

            using (var client = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest2))
            {
                var config = new AWSLoggerConfig(logGroupName)
                {
                    Region = RegionEndpoint.USWest2.SystemName,
                    DisableLogGroupCreation = false,
                };

                var core = new AWSLoggerCore(config, "unit");
                core.AddMessage("Test message added at " + DateTimeOffset.UtcNow.ToString());
                core.Flush();
                _testFixure.LogGroupNameList.Add(logGroupName); // let's enlist the auto-created group for deletion.
                core.Close();
            }
        }