Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same log file in multiple projects using serilog

Tags:

c#

serilog

I have a Logger.cs class:

public Logger(string logtype=null)
        {
            _logtype = logtype;
            LogEventLevel level = LogEventLevel.Warning;
            if (File.Exists(configPath))
            {
                XDocument xdoc = XDocument.Load(configPath);
                string val = xdoc.Descendants("logEnabled").First().Value;
                // if(clientConfig.LogEnabled == true)
                if (val == "true")
                {
                    level = LogEventLevel.Debug;

                }
                else if (val == "false")
                {
                    level = LogEventLevel.Warning;
                }
            }
            else
            {
                level = LogEventLevel.Warning;
            }
           _logger = new LoggerConfiguration()
                        .MinimumLevel.Debug()
                         .WriteTo.File(_filepath, level)
                         .CreateLogger();

        }

this logger class is used in multiple projects in a solution. Like shown below:

    Class A {
     Logger _logger = new Logger("A");
    }

Class A1 {
     Logger _logger = new Logger("A");
    }

Class B {
     Logger _logger = new Logger("B");
    }

Class B1 {
     Logger _logger = new Logger("A");
    }

With my above code. Now i can see only the first logging is written to the log file. Class A and Class A1 are using the same log file "A", when my program executes i can see only Class A logging is present in the log but not class A1 logging messages. Same for Class B and Class B1, only class B messages are visible.

How can i use the same log file across multiple project in a solution?

like image 620
Rem San Avatar asked Mar 19 '19 05:03

Rem San


1 Answers

You will need to enable multi-process shared log files, set shared to true

_logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.File(_filepath, level, shared: true)
                .CreateLogger();

For more check Shared log files

like image 150
ElasticCode Avatar answered Oct 16 '22 19:10

ElasticCode