DefaultLogStreamProvider

We found 10 examples in language CSharp for this search. You will see 30 fragments of code.

        public string GetLogStreamName()
        {
            var ec2_id = Environment.GetEnvironmentVariable("EC2_ID");
            if (string.IsNullOrWhiteSpace(ec2_id)) return defaultLogStreamProvider.GetLogStreamName();
            return $"{DateTime.UtcNow.ToString("yyyy-MM-dd-HH-mm-ss")}-EC2-{ec2_id}";
        }


        public static void Main(string[] args)
        {
            Log.Logger = CreateLogger();

            try
            {
                CreateWebHostBuilder(args).Build().Run();
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static Logger CreateLogger()
        {
            var group = "Context";
            var application = "API.Context";

#if (!DEBUG)
            var client = Configuration.GetAWSOptions().CreateServiceClient<IAmazonCloudWatchLogs>();

            var options = new CloudWatchSinkOptions
            {
                LogGroupName = $"Applications/{group}/{application}",
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                BatchSizeLimit = 100,
                QueueSizeLimit = 10000,
                RetryAttempts = 3,
                LogGroupRetentionPolicy = LogGroupRetentionPolicy.FiveDays,
                TextFormatter = new JsonFormatter(),
                MinimumLogEventLevel = LogEventLevel.Information
            };   
#endif
            return new LoggerConfiguration()
                .Enrich.FromLogContext()
                .Enrich.WithProperty("Application", application)
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Debug()
                .WriteTo.Console(
                    outputTemplate: "{NewLine}[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Scope} {Message}{NewLine}{Exception}"
                )
#if (!DEBUG)
                .WriteTo.AmazonCloudWatch(options, client)
#endif
                .CreateLogger();
        }

        private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseSerilog()
                .UseStartup<Startup>();

        public static LoggerConfiguration BuildEmptyLoggerConfiguration()
        {
            return new LoggerConfiguration();
        }

        public static ILogger CreateLogger(LoggerConfiguration loggerConfiguration, LogEventLevel minimumLogEventLevel)
        {
            return loggerConfiguration
                .MinimumLevel.Is(minimumLogEventLevel)
                .CreateLogger();
        }

        public static LoggerConfiguration AppendFileLogger(this LoggerConfiguration logger,
                                                           string logFilePath,
                                                           int retainedFileCountLimit = 14)
        {
            return logger
                .WriteTo.File(path: logFilePath,
                              rollingInterval: RollingInterval.Day,
                              formatter: new CompactJsonFormatter(),
                              retainedFileCountLimit: retainedFileCountLimit);
        }

        public static LoggerConfiguration AppendConsoleLogger(this LoggerConfiguration logger)
        {
            return logger
                    .WriteTo
                    .Console();
        }

        public static LoggerConfiguration AppendAwsCloudwatchLogger(this LoggerConfiguration logger,
                                                                    string logGroupName,
                                                                    string environmentName,
                                                                    LogEventLevel minimumLogEvent)
        {
            logGroupName = $"{logGroupName}/{environmentName}".ToLower();

            var formatter = new CompactJsonFormatter();
            var options = new CloudWatchSinkOptions
            {
                LogGroupName = logGroupName,
                TextFormatter = formatter,
                MinimumLogEventLevel = minimumLogEvent,
                BatchSizeLimit = 100,
                QueueSizeLimit = 10000,
                Period = TimeSpan.FromSeconds(10),
                CreateLogGroup = true,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts = 5,
                LogGroupRetentionPolicy = LogGroupRetentionPolicy.OneDay
            };

            var client = new AmazonCloudWatchLogsClient(RegionEndpoint.SAEast1);

            return logger
                .WriteTo.AmazonCloudWatch(options, client);
        }


        public void Write(LogEventLevel information, string v, LogEntry entry)
        {
            _logger.Write(information, v, entry);
        }

        public static LoggerConfiguration BuildEmptyLoggerConfiguration()
        {
            return new LoggerConfiguration();
        }

        public static ILogger CreateLogger(LoggerConfiguration loggerConfiguration, LogEventLevel minimumLogEventLevel)
        {
            return loggerConfiguration
                .MinimumLevel.Is(minimumLogEventLevel)
                .CreateLogger();
        }

        public static LoggerConfiguration AppendFileLogger(this LoggerConfiguration logger,
                                                           string logFilePath,
                                                           int retainedFileCountLimit = 14)
        {
            return logger
                .WriteTo.File(path: logFilePath,
                              rollingInterval: RollingInterval.Day,
                              formatter: new CompactJsonFormatter(),
                              retainedFileCountLimit: retainedFileCountLimit);
        }

        public static LoggerConfiguration AppendConsoleLogger(this LoggerConfiguration logger)
        {
            return logger
                    .Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("health")))
                    .WriteTo.Console();
        }

        public static LoggerConfiguration AppendAwsCloudwatchLogger(this LoggerConfiguration logger,
                                                                    string logGroupName,
                                                                    string environmentName,
                                                                    LogEventLevel minimumLogEvent)
        {
            logGroupName = $"{logGroupName}/{environmentName}".ToLower();

            var formatter = new CompactJsonFormatter();
            var options = new CloudWatchSinkOptions
            {
                LogGroupName = logGroupName,
                TextFormatter = formatter,
                MinimumLogEventLevel = minimumLogEvent,
                BatchSizeLimit = 100,
                QueueSizeLimit = 10000,
                Period = TimeSpan.FromSeconds(10),
                CreateLogGroup = true,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts = 5,
                LogGroupRetentionPolicy = LogGroupRetentionPolicy.OneDay
            };

            var client = new AmazonCloudWatchLogsClient(RegionEndpoint.SAEast1);

            return logger
                .WriteTo.AmazonCloudWatch(options, client);
        }

        public static ILogger CreateLogger(LoggerSettings settings)
        {
            var logLevel = typeof(LogEventLevel).IsEnumDefined(settings.MinimumLogLevel) ?
                                Enum.Parse<LogEventLevel>(settings.MinimumLogLevel) : LogEventLevel.Error;
            var retentionPolicy = typeof(LogGroupRetentionPolicy).IsEnumDefined(settings.RetentionPolicy) ?
                              Enum.Parse<LogGroupRetentionPolicy>(settings.RetentionPolicy): LogGroupRetentionPolicy.OneWeek;
            var region = RegionEndpoint.GetBySystemName(settings.Region);
            var levelSwitch = new LoggingLevelSwitch();
            levelSwitch.MinimumLevel = logLevel;
 
            var options = new CloudWatchSinkOptions
            {
                LogGroupName = settings.LogGroup,
                MinimumLogEventLevel = logLevel,
                BatchSizeLimit = 100,
                QueueSizeLimit = 10000,
                Period = TimeSpan.FromSeconds(10),
                CreateLogGroup = true,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts = 5,
                LogGroupRetentionPolicy = retentionPolicy
            };

            var client = new AmazonCloudWatchLogsClient(region);
            
            return new LoggerConfiguration()
                .WriteTo.Logger(l1 => l1
                    .MinimumLevel.ControlledBy(levelSwitch)
                    .WriteTo.AmazonCloudWatch(options, client))
              .CreateLogger();
        }

        public static LoggerConfiguration BuildEmptyLoggerConfiguration()
        {
            return new LoggerConfiguration();
        }

        public static ILogger CreateLogger(LoggerConfiguration loggerConfiguration, LogEventLevel minimumLogEventLevel)
        {
            return loggerConfiguration
                .MinimumLevel.Is(minimumLogEventLevel)
                .CreateLogger();
        }

        public static LoggerConfiguration AppendFileLogger(this LoggerConfiguration logger, string logFilePath, int retainedFileCountLimit = 14)
        {
            return logger
                .WriteTo.RollingFile(pathFormat: logFilePath, formatter: new CompactJsonFormatter(), retainedFileCountLimit: retainedFileCountLimit);
        }

        public static LoggerConfiguration AppendConsoleLogger(this LoggerConfiguration logger)
        {
            return logger
                .WriteTo.Console(formatter: new CompactJsonFormatter());
        }

        public static LoggerConfiguration AppendAwsCloudwatchLogger(this LoggerConfiguration logger, string logGroupName, LogEventLevel minimumLogEvent, string accessKey, string securityKey)
        {
            // customer formatter
            var formatter = new CompactJsonFormatter();

            // options for the sink defaults in https://github.com/Cimpress-MCP/serilog-sinks-awscloudwatch/blob/master/src/Serilog.Sinks.AwsCloudWatch/CloudWatchSinkOptions.cs
            var options = new CloudWatchSinkOptions
            {
                LogGroupName = logGroupName,
                TextFormatter = formatter,
                MinimumLogEventLevel = minimumLogEvent,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts = 5
            };

            var credentials = new BasicAWSCredentials(accessKey, securityKey);

            // setup AWS CloudWatch client
            var client = new AmazonCloudWatchLogsClient(credentials, RegionEndpoint.EUWest1);

            return logger
                .WriteTo.AmazonCloudWatch(options, client);
        }

        public static LoggerConfiguration AppendElasticsearchLogger(this LoggerConfiguration logger, string uri, string indexName)
        {
            var options = new ElasticsearchSinkOptions(new Uri(uri))
            {
                IndexFormat = $"{indexName}-{0:yyyy.MM}",
            };

            return logger
                .WriteTo.Elasticsearch(options);
        }

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<AWSCloudWatchAPI>();

            builder.Register(context =>
            {
                var awsCloudWatchOptions = context.Resolve<AWSCloudWatchOptions>();
                BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(awsCloudWatchOptions.Key, awsCloudWatchOptions.Secret);
                return new AmazonCloudWatchLogsClient(basicAWSCredentials, RegionEndpoint.GetBySystemName(awsCloudWatchOptions.Region));
            });

            builder.Register<ILogger>(context =>
            {
                var options = context.Resolve<CloudWatchSinkOptions>();
                options.Period = TimeSpan.FromSeconds(10);
                options.LogStreamNameProvider = new EC2LogStreamNameProvider(); // new DefaultLogStreamProvider();
                options.TextFormatter = new JsonFormatter();
                var client = context.Resolve<AmazonCloudWatchLogsClient>();
                Log.Logger = new LoggerConfiguration()
                    .WriteTo.ColoredConsole(LogEventLevel.Verbose)
                    .WriteTo.AmazonCloudWatch(options, client)
                    .CreateLogger();
                return Log.Logger;
            });

            builder.Register(context =>
            {
                var logger =  context.Resolve<ILogger>();
                var genericLogger = new GenericLogger()
                {
                    Info = value => logger.Information(value),
                    Verbose = value => logger.Verbose(value),
                    Error = value => logger.Error(value),
                    Warn = value => logger.Warning(value),
                    Log = value => logger.Debug(value),
                };
                Common.Logging.Console.Logger = genericLogger;
                return genericLogger;
            });


        }

        // ReSharper disable once UnusedMember.Global
        public static LoggerConfiguration CloudWatch
            (
                this LoggerSinkConfiguration sinkConfiguration,
                string logGroupName,
                string regionEndpointSystemName,
                bool createLogGroup = true,
                LogEventLevel restrictedToMinimumLevel = LogEventLevel.Information,
                int batchSizeLimit = 100,
                int queueSizeLimit = 10000,
                byte retryAttempts = 5,
                TimeSpan? period = null,
                string logStreamNameProviderFqn = null,
                string textFormatterFqn = null
            )
        {
            ILogStreamNameProvider GetLogStreamNameProvider()
            {
                if (string.IsNullOrEmpty(logStreamNameProviderFqn))
                {
                    return new DefaultLogStreamProvider();
                }

                var logStreamNameProviderType = Type.GetType(logStreamNameProviderFqn);

                return
                    (ILogStreamNameProvider)
                        Activator
                            .CreateInstance(logStreamNameProviderType ?? throw new ArgumentNullException(nameof(logStreamNameProviderType)));
            }

            ITextFormatter GetTextFormatter()
            {
                if (string.IsNullOrEmpty(textFormatterFqn))
                {
                    return new JsonFormatter();
                }

                var textFormatterType = Type.GetType(textFormatterFqn);

                return
                    (ITextFormatter)
                        Activator
                            .CreateInstance(textFormatterType ?? throw new ArgumentNullException(nameof(textFormatterType)));
            }

            var options = new CloudWatchSinkOptions
            {
                LogGroupName = logGroupName,
                TextFormatter = GetTextFormatter(),
                MinimumLogEventLevel = restrictedToMinimumLevel,
                BatchSizeLimit = batchSizeLimit,
                QueueSizeLimit = queueSizeLimit,
                Period = period ?? CloudWatchSinkOptions.DefaultPeriod,
                CreateLogGroup = createLogGroup,
                LogStreamNameProvider = GetLogStreamNameProvider(),
                RetryAttempts = retryAttempts
            };

            var endPoint = RegionEndpoint.GetBySystemName(regionEndpointSystemName);
            var client = CloudWatchLogsClientExtensions.ClientFactory.Invoke(endPoint);

            return 
                sinkConfiguration
                    .Sink
                    (
                        new CloudWatchLogSink(client, options), 
                        options.MinimumLogEventLevel
                    );
        }

        public static IServiceCollection AddNowProvider(this IServiceCollection collection)
        {
            collection.AddSingleton<INowProvider, NowProvider>();
            return collection;
        }

        public static IServiceCollection AddRandomWordsProvider(this IServiceCollection collection)
        {
            var random = new Random();
            collection.AddSingleton<IRandomisedWordProvider>(new RandomisedWordProvider(random));
            return collection;
        }
            public void Format(LogEvent logEvent, TextWriter output)
            {
                output.Write("Timestamp - {0} | Level - {1} | Message {2} {3}", logEvent.Timestamp, logEvent.Level, logEvent.MessageTemplate, output.NewLine);
                if (logEvent.Exception != null)
                {
                    output.Write("Exception - {0}", logEvent.Exception);
                }
            }

        public static IServiceCollection AddLogger(this IServiceCollection collection, IConfiguration configuration)
        {
            var logConfig = new LoggerConfiguration();
            var sink = configuration["Logging:Sink"];

            switch(sink)
            {
                case "AWSCloudWatch":
                    var accessKeyId = configuration["AWS:AccessKeyId"];
                    var accessSecretAccessKey = configuration["AWS:AccessSecretAccessKey"];

                    var client = new AmazonCloudWatchLogsClient(accessKeyId, accessSecretAccessKey, RegionEndpoint.EUWest2);
                    var options = new CloudWatchSinkOptions
                    {
                        LogGroupName = "shared-list-beanstalk-log/ShareListApi-env",
                        Period = TimeSpan.FromSeconds(10),
                        BatchSizeLimit = 100,
                        QueueSizeLimit = 10000,
                        LogStreamNameProvider = new DefaultLogStreamProvider(),
                        RetryAttempts = 5,
                        CreateLogGroup = true,
                        TextFormatter = new AWSTextFormatter(),
                    };

                    logConfig.WriteTo.AmazonCloudWatch(options, client);
                    break;
                default:
                    logConfig.WriteTo.RollingFile(Path.Combine(AppContext.BaseDirectory, "log-{Date}.log"));
                    break;
            }

            collection.AddSingleton<ILogger>(logConfig.CreateLogger());
            return collection;
        }

        public static IServiceCollection AddDbLogger(this IServiceCollection collection, string connectionString)
        {
            var logger = new LoggerConfiguration()
                .WriteTo.MSSqlServer(connectionString);
            return collection;
        }

        public static IServiceCollection AddConfiguration(this IServiceCollection collection, IConfiguration configuration)
        {
            collection.AddSingleton(configuration);
            return collection;
        }

Serilog.Sinks.AwsCloudWatch.DefaultLogStreamProvider : ILogStreamNameProvider

Constructors :

public DefaultLogStreamProvider()

Methods :

public String GetLogStreamName()
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()