1

I have 8 console projects in one solution(I'm planning to convert them to services in future) referencing each other. I'm planning to create a ILogger interface and Logger class to encapsulate Nlog methods as I don't want to reference nlog in every project. And pass this interface from Core project to every other as build parameter. Something like

using Core
...
ILogger logger = new Logger();

Questions are:

1) Can I use one config for every logger? I use ideas from here. Mainly caller info attributes to get the assembly name, etc. So I don't need different log files or settings to determine log's origin.

2) And should I go this way and create 8 instances of ILogger, instead of creating on static class in Core assembly and calling it's methods each time as I need it. I already reference Core in every other assembly, so no new references will be made. My concern with 8 ILoggers is concurrent write to one file/DB.

  • Possible duplicate of [How to use NLog from multiple projects in the same solution](https://stackoverflow.com/questions/29188721/how-to-use-nlog-from-multiple-projects-in-the-same-solution) – Hoshani Sep 30 '19 at 11:23

2 Answers2

1

1) Can I use one config for every logger? I use ideas from here. Mainly caller info attributes to get the assembly name, etc. So I don't need different log files or settings to determine log's origin.

Yes, the config should be there in the startup project of the solution.

2) And should I go this way and create 8 instances of ILogger, instead of creating on static class in Core assembly and calling it's methods each time as I need it. I already reference Core in every other assembly, so no new references will be made.

Instance per class is recommend. You could use LogManager.GetLogger(myClassName), otherwise it's difficult the trace where the logs are from and difficult to filter.

My concern with 8 ILoggers is concurrent write to one file/DB.

You could group the messages in a buffering target so the writes are grouped. See the docs of the Buffering Wrapper target

Julian
  • 33,915
  • 22
  • 119
  • 174
0

I used using Microsoft.Extensions.Logging in my solution in all with 11 projects with dependency injection. I normally configured in startup.cs file and put the nlog.config in the startup project. in other projects, for example, repository project, i used like below:

public class ReceiptRepository : IReceiptRepository
{
    private readonly ReceiptContext _context;
   private readonly ILogger<ReceiptRepository> _logger;

    public ReceiptRepository(ReceiptContext context , ILogger<ReceiptRepository> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<ReceiptData> CreateReceiptAsync(ReceiptData receipt, CancellationToken token)
    {
       ...

       _logger.LogInformation($"ReceiptRepository::CreateReceiptAsync::{receipt.Id}:: is added to repository");

        return receipt;
    }
Hanieh Variani
  • 101
  • 1
  • 5