Esempio n. 1
0
        public void CanFormat()
        {
#if NET5_0_OR_GREATER
            var ver = Environment.Version.ToString();
#else
            var ver = AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName;
#endif
            const string apiKey       = "NOT_AN_API_KEY";
            var          config       = new DatadogConfiguration();
            var          logFormatter = new LogFormatter(ver, "TEST", "localhost", new[] { "the", "coolest", "test" });
            var          noop         = new NoopClient(apiKey, logFormatter);
            using (var log = new LoggerConfiguration().WriteTo.DatadogLogs(apiKey, configuration: config, client: noop).CreateLogger())
            {
                var positions = new dynamic[]
                {
                    new { Latitude = byte.MinValue, Longitude = byte.MaxValue },
                    new { Latitude = short.MinValue, Longitude = short.MaxValue },
                    new { Latitude = int.MinValue, Longitude = int.MaxValue },
                    new { Latitude = long.MinValue, Longitude = long.MaxValue }
                };
                const int elapsedMs = 34;
                Assert.DoesNotThrow(() => log.Information("Processed {@Positions} in {Elapsed:000} ms.", new Dictionary <string, object>
                {
                    { "positions", positions },
                    { "creator", "ACME" }
                }, elapsedMs));
            }
        }
    /// <summary>
    /// Adds the datadog using the specified logger for Serilog
    /// </summary>
    /// <param name="logger">The logger</param>
    /// <param name="config">The datadog logger</param>
    /// <returns>The logger</returns>
    private static LoggerConfiguration AddDatadog(
        this LoggerConfiguration logger,
        DataDogConfig config
        )
    {
        var datadogKey = config.ApiKey;

        if (!config.IsEnabled)
        {
            return(logger);
        }
        if (datadogKey == "YOUR_API_KEY" &&
            !datadogKey.IsNotNullOrEmpty())
        {
            return(logger);
        }

        var datadogConfiguration = new DatadogConfiguration(
            url: DataDogHost,
            port: 10516,
            useSSL: true,
            useTCP: true
            );

        logger.WriteTo.DatadogLogs(
            apiKey: datadogKey,
            service: "TelegramBot",
            source: config.Source,
            host: config.Host,
            tags: config.Tags.ToArray(),
            configuration: datadogConfiguration
            );

        return(logger);
    }
Esempio n. 3
0
        /// <summary>
        /// Adds a sink that sends log events to Datadog.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="apiKey">Your Datadog API key.</param>
        /// <param name="source">The integration name.</param>
        /// <param name="service">The service name.</param>
        /// <param name="host">The host name.</param>
        /// <param name="tags">Custom tags.</param>
        /// <param name="configuration">The Datadog logs client configuration.</param>
        /// <param name="logLevel">The minimum log level for the sink.</param>
        /// <param name="batchSizeLimit">The maximum number of events to emit in a single batch.</param>
        /// <param name="batchPeriod">The time to wait before emitting a new event batch.</param>
        /// <param name="queueLimit">
        /// Maximum number of events to hold in the sink's internal queue, or <c>null</c>
        /// for an unbounded queue. The default is <c>10000</c>
        /// </param>
        /// <param name="exceptionHandler">This function is called when an exception occurs when using
        /// DatadogConfiguration.UseTCP=false (the default configuration)</param>
        /// <param name="detectTCPDisconnection">Detect when the TCP connection is lost and recreate a new connection.</param>
        /// <returns>Logger configuration</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration DatadogLogs(
            this LoggerSinkConfiguration loggerConfiguration,
            string apiKey,
            string source  = null,
            string service = null,
            string host    = null,
            string[] tags  = null,
            DatadogConfiguration configuration = null,
            LogEventLevel logLevel             = LevelAlias.Minimum,
            int?batchSizeLimit   = null,
            TimeSpan?batchPeriod = null,
            int?queueLimit       = null,
            Action <Exception> exceptionHandler = null,
            bool detectTCPDisconnection         = false)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            configuration = (configuration != null) ? configuration : new DatadogConfiguration();
            var sink = DatadogSink.Create(apiKey, source, service, host, tags, configuration, batchSizeLimit, batchPeriod, queueLimit, exceptionHandler, detectTCPDisconnection);

            return(loggerConfiguration.Sink(sink, logLevel));
        }
Esempio n. 4
0
        /// <summary>
        /// Adds a sink that sends log events to Datadog.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="apiKey">Your Datadog API key.</param>
        /// <param name="source">The integration name.</param>
        /// <param name="service">The service name.</param>
        /// <param name="host">The host name.</param>
        /// <param name="tags">Custom tags.</param>
        /// <param name="configuration">The Datadog logs client configuration.</param>
        /// <param name="configurationSection">A config section defining the datadog configuration.</param>
        /// <param name="logLevel">The minimum log level for the sink.</param>
        /// <param name="batchSizeLimit">The maximum number of events to emit in a single batch.</param>
        /// <param name="batchPeriod">The time to wait before emitting a new event batch.</param>
        /// <param name="queueLimit">
        /// Maximum number of events to hold in the sink's internal queue, or <c>null</c>
        /// for an unbounded queue. The default is <c>10000</c>
        /// </param>
        /// <param name="exceptionHandler">This function is called when an exception occurs when using
        /// DatadogConfiguration.UseTCP=false (the default configuration)</param>
        /// <returns>Logger configuration</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration DatadogLogs(
            this LoggerSinkConfiguration loggerConfiguration,
            string apiKey,
            string source  = null,
            string service = null,
            string host    = null,
            string[] tags  = null,
            DatadogConfiguration configuration         = null,
            IConfigurationSection configurationSection = null,
            LogEventLevel logLevel = LevelAlias.Minimum,
            int?batchSizeLimit     = null,
            TimeSpan?batchPeriod   = null,
            int?queueLimit         = null,
            Action <Exception> exceptionHandler = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            var config = ApplyMicrosoftExtensionsConfiguration.ConfigureDatadogConfiguration(configuration, configurationSection);
            var sink   = DatadogSink.Create(apiKey, source, service, host, tags, config, batchSizeLimit, batchPeriod, queueLimit, exceptionHandler);

            return(loggerConfiguration.Sink(sink, logLevel));
        }
Esempio n. 5
0
        public static void SetupLogger()
        {
            var consoleStamp    = "[{Timestamp:yyyy-MM-dd HH:mm:ss.ffff zzz}";
            var outputTemplate  = $"{consoleStamp} {{Level:u3}}] {{Message:lj}}{{NewLine}}{{Exception}}";
            var logPath         = "Storage/Logs/ZiziBot-.log";
            var flushInterval   = TimeSpan.FromSeconds(1);
            var rollingInterval = RollingInterval.Day;
            var datadogKey      = BotSettings.DatadogApiKey;
            var rollingFile     = 50 * 1024 * 1024;

            var serilogConfig = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .WriteTo.Console(theme: SystemConsoleTheme.Colored, outputTemplate: outputTemplate)
                                .WriteTo.File(logPath, rollingInterval: rollingInterval, flushToDiskInterval: flushInterval,
                                              shared: true, fileSizeLimitBytes: rollingFile, outputTemplate: outputTemplate);

            if (BotSettings.IsProduction)
            {
                serilogConfig = serilogConfig
                                .MinimumLevel.Debug()
                                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                                .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Information)
                                .MinimumLevel.Override("Hangfire", LogEventLevel.Information);
            }
            else
            {
                serilogConfig = serilogConfig
                                .MinimumLevel.Debug()
                                .MinimumLevel.Override("Microsoft", LogEventLevel.Debug)
                                .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Debug)
                                .MinimumLevel.Override("Hangfire", LogEventLevel.Information);
            }

            if (datadogKey != "YOUR_API_KEY" || datadogKey.IsNotNullOrEmpty())
            {
                var dataDogHost = "intake.logs.datadoghq.com";
                var config      = new DatadogConfiguration(url: dataDogHost, port: 10516, useSSL: true, useTCP: true);
                serilogConfig.WriteTo.DatadogLogs(
                    apiKey: datadogKey,
                    service: "TelegramBot",
                    source: BotSettings.DatadogSource,
                    host: BotSettings.DatadogHost,
                    tags: BotSettings.DatadogTags.ToArray(),
                    configuration: config);
            }

            Log.Logger = serilogConfig.CreateLogger();
        }
        /// <summary>
        /// Adds a sink that sends log events to Datadog.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="apiKey">Your Datadog API key.</param>
        /// <param name="configuration">The Datadog logs client configuration.</param>
        /// <returns>Logger configuration</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration DatadogLogs(
            this LoggerSinkConfiguration loggerConfiguration,
            string apiKey,
            DatadogConfiguration configuration = null,
            LogEventLevel logLevel             = LevelAlias.Minimum)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            configuration = (configuration != null) ? configuration : new DatadogConfiguration();
            return(loggerConfiguration.Sink(new DatadogSink(apiKey, configuration), logLevel));
        }
        /// <summary>
        /// Adds a sink that sends log events via datadog.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="datadogConfiguration">The configuration used for writing events to datadog.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
        /// <param name="period">The time to wait between checking for event batches.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <returns>Logger configuration, allowing datadogConfiguration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration Datadog(
            this LoggerSinkConfiguration loggerConfiguration,
            DatadogConfiguration datadogConfiguration,
            string outputTemplate = DefaultOutputTemplate,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit          = DatadogSink.DefaultBatchPostingLimit,
            TimeSpan?period                = null,
            IFormatProvider formatProvider = null)
        {
            if (datadogConfiguration == null)
            {
                throw new ArgumentNullException("datadogConfiguration");
            }

            var defaultedPeriod = period ?? DatadogSink.DefaultPeriod;
            var formatter       = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            var datadogSink     = new DatadogSink(datadogConfiguration, batchPostingLimit, defaultedPeriod, formatter);

            return(loggerConfiguration.Sink(datadogSink, restrictedToMinimumLevel));
        }
Esempio n. 8
0
        public static void Main(string[] args)
        {
            //var configuration = new ConfigurationBuilder()
            //    .SetBasePath(Directory.GetCurrentDirectory())
            //    .AddJsonFile("appsettings.json")
            //    //.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", true)
            //    .Build();

            //var logger = new LoggerConfiguration()
            //    .ReadFrom.Configuration(configuration)
            //    .CreateLogger();

            var config = new DatadogConfiguration("https://http-intake.logs.datadoghq.eu");

            Serilog.Log.Logger = new LoggerConfiguration()
                                 .WriteTo.DatadogLogs("aa2c854cd23949b8ce4f089bd2042847", configuration: config)
                                 .CreateLogger();

            Serilog.Log.Logger.Information("Hello, from program.cs after docker support!");
            CreateHostBuilder(args).Build().Run();
        }
Esempio n. 9
0
        /// <summary>
        /// Adds a sink that sends log events to Datadog.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="apiKey">Your Datadog API key.</param>
        /// <param name="source">The integration name.</param>
        /// <param name="service">The service name.</param>
        /// <param name="host">The host name.</param>
        /// <param name="tags">Custom tags.</param>
        /// <param name="configuration">The Datadog logs client configuration.</param>
        /// <param name="configurationSection">A config section defining the datadog configuration.</param>
        /// <returns>Logger configuration</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration DatadogLogs(
            this LoggerSinkConfiguration loggerConfiguration,
            string apiKey,
            string source  = null,
            string service = null,
            string host    = null,
            string[] tags  = null,
            DatadogConfiguration configuration         = null,
            IConfigurationSection configurationSection = null,
            LogEventLevel logLevel = LevelAlias.Minimum)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            var config = ApplyMicrosoftExtensionsConfiguration.ConfigureDatadogConfiguration(configuration, configurationSection);

            return(loggerConfiguration.Sink(new DatadogSink(apiKey, source, service, host, tags, config), logLevel));
        }