How to connect Sentry to NLog in a .Net 5 project

Viewed 302

I'm trying to connect Sentry to NLog. I'd like to write the logs with a level under Warning in a file text and the others in Sentry.

This is my NLogConfiguration file:

            public static LoggingConfiguration ConfigureTarget()
        {
            var config = new LoggingConfiguration();
            var fileTarget = new FileTarget
            {
                FileName = "${basedir}\\Logger\\internal_logs\\Newfile.txt",
                Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}",
            };
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget, "*", false);
            var starget = new Sentry.NLog.SentryTarget
            {
                Dsn = "https://xxx@xxx.ingest.sentry.io/xxx",
                MinimumEventLevel = "information",
                Layout = "${message}"
            };
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, starget, "*", false);
           
            LogManager.Configuration = config;

            LogManager.ReconfigExistingLoggers();
            Sentry.SentrySdk.Init();

            return config;
        }

This is my program.cs:

    public class Program
    {
        public static void Main(string[] args)
        {
            NLog.Config.LoggingConfiguration config = NLogConfiguration.ConfigureTarget();
            var logger = NLog.Web.NLogBuilder.ConfigureNLog(config).GetCurrentClassLogger();
            try
            {
                logger.Debug("init main");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                })
                .UseNLog();

and this is my startup:

        public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "NLogSentryExercise", Version = "v1" });
            });
        }

       
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "NLogSentryExercise v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

I tried also to follow the official documentation but maybe I made some mistakes (https://docs.sentry.io/platforms/dotnet/guides/nlog/). Could anyone help me please? Thanks

1 Answers

I resolved in this way:

        public static LoggingConfiguration ConfigureTarget()
        {
            var config = new LoggingConfiguration();
            var fileTarget = new FileTarget
            {
                FileName = "${basedir}\\Logger\\internal_logs\\logFile.txt",
                Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}",
            };
            config.AddRule(LogLevel.Trace, LogLevel.Info, fileTarget, "*", false);
            config.AddSentry(o =>
                {
                    o.Dsn = "https://xxx@xxx.ingest.sentry.io/xxx";
                    o.Layout = "${message}";
                    o.BreadcrumbLayout = "${logger}: ${message}";
                    o.MinimumBreadcrumbLevel = LogLevel.Info;
                    o.MinimumEventLevel = LogLevel.Warn;
                    o.AddTag("logger", "${logger}");
                });
            return config;
        }

It works.

Related