1

I have a problem I have two classes and I want to write both classes into a Serilog file.

class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                    .WriteTo.RollingFile(logs\\log.txt)
                    .CreateLogger();
            Log.Information("TEST");
        }
    }

public class data: IData
    {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.RollingFile(logs\\log.txt)
                .CreateLogger();
            Log.Information("_________________________________________________");
            Log.Information("I'm right now in the Class", DateTime.Now);
    }

If I were to write this, I would create two log objects and the log information, would be written in different files. So my question is how can I create only one log object that I can use in both classes and that the log information write in only one file.

2 Answers2

1

There is no need to create new log file. This log file is already exists you can append it.

Kushan
  • 10,657
  • 4
  • 37
  • 41
0

I had this same problem on my .net application. My solution was to create a class with a private static Logger. It lookes like this:

public class ErrorLogRepository
    {
        private static Logger _logger;

        public ErrorLogRepository()
        {
            if(_logger == null)
            {
                _logger = new LoggerConfiguration()
                    .WriteTo.RollingFile(logs\\log.txt)
                    .CreateLogger();
            } 
        }

        public void Log()
        {
            Log.Information("I'm right now in the Class", DateTime.Now);
        }
    }

With this class, everytime you create an instance of it, the constructor will validate if a Logger has been created before. That way, you will always use the same Logger for different classe, and you will always write on the same file.

mvoelcker
  • 330
  • 4
  • 8