Cysharp / ZLogger

Zero Allocation Text/Structured Logger for .NET with StringInterpolation and Source Generator, built on top of a Microsoft.Extensions.Logging.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Separate outputs for loggers

robertmircea opened this issue · comments

Is it possible to separate loggers output in multiple files?

For example, I want the "ProtoLogger" to write to a file named protocol.log and the rest of the application to write to a different file e.g app.log.

I had the same thought, and this seems to work:

public static void CreateLogger(
string filename
, string prefix
, out ILoggerFactory factory
, out ILogger logger)
{
    factory = UnityLoggerFactory.Create(builder =>
    {
        builder.SetMinimumLevel(LogLevel.Trace);
        builder.AddZLoggerFile(filename, "file-plain", x => { x.PrefixFormatter = (writer, info) => ZString.Utf8Format(writer, "[{0} {1} {2}][{3}]", info.Timestamp.ToLocalTime().DateTime, MainThreadActionQueue.frameNumber, Misc.GetLongTime(), prefix); });
    });

    logger = factory.CreateLogger(filename);
    Application.quitting += factory.Dispose;

}

then I created the logs somewhere else:

        LogManager.CreateLogger("LoggerA.log", "LOGGER_A",out LoggerAFactory , out LoggerALogger);
        LogManager.CreateLogger("LoggerB.log", "LOGGER_B",out LoggerBFactory, out LoggerBLogger);

        LoggerALogger.ZLogDebug("Init Logger A");
        LoggerBLogger.ZLogDebug("Init Logger B");

while holding the static handles:

    static ILogger LoggerALogger, LoggerBLogger;
    static ILoggerFactory LoggerAFactory, LoggerBFactory;

then I also needed to close them (so i can send them to the server), and then create new ones with a new name so i did

    void GenerateNextLog()
    {
        LoggerAFactory.Dispose();
        LoggerBFactory.Dispose();
        Application.quitting -= LoggerAFactory.Dispose;
        Application.quitting -= LoggerBFactory.Dispose;


        LogManager.CreateLogger("LoggerA2.log", "LOGGER_A", out LoggerAFactory, out LoggerALogger);
        LogManager.CreateLogger("LoggerB2.log", "LOGGER_B", out LoggerBFactory, out LoggerBLogger);

        LoggerALogger.ZLogDebug("Init Logger A 2");
        LoggerBLogger.ZLogDebug("Init Logger B 2");

    }