简体   繁体   中英

Using NLog for several projects on one solution c#

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.

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

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM