SergiusTheBest / plog

Portable, simple and extensible C++ logging library
MIT License
2.21k stars 391 forks source link

[Question] How to add custom prefix (record) information? #271

Closed yanlusu closed 1 year ago

yanlusu commented 1 year ago

How to add custom prefix (record) information?

Just like:

2023-09-24 16:58:34.818 DEBUG [16708] [main@37] [Default] This is a message from the Default facility
2023-09-24 16:58:34.820 DEBUG [16708] [main@38] [Default] This is a message from the Default facility too because Default = 0
2023-09-24 16:58:34.821 WARN  [16708] [main@40] [Auth] This is a message from the Auth facility
2023-09-24 16:58:34.822 INFO  [16708] [main@41] [FileIO] This is a message from the FileIO facility

and I don't want to add to every PLOG statement. what I want maybe like this:

PLOGD_FAC_DEF(...)
PLOGD_FAC_Auth(...)
PLOGD_FAC_FileIO(...)

I know I can use macro to implement it, but it's not good, and I cannot use other feature such as condition log;

#define PLOGD_MODULE(module_name) PLOGD.printf("[%s] ", (module_name))

Is there a general solution to this?

thanks.

SergiusTheBest commented 1 year ago

One of the solutions is to create several logger instances (if you know module names at compile time):

https://github.com/SergiusTheBest/plog/blob/0d9baad55cab98a7507d67d2d7934945da687a2b/samples/MultiInstance/Main.cpp#L8-L26

Thus you can control severity and turn on/off log messages per module name. Then you need to create a new formatter class and specify there a new field:

ss << PLOG_NSTR("[") << instanceIdToString(record.getInstanceId()) << PLOG_NSTR("] ");

and implement instanceIdToString. It could look like this:

    inline const char* instanceIdToString(int instanceId)
    {
        switch (instanceId)
        {
        case Auth:
            return "Auth;
        case FileIO:
            return "FileIO";
        default:
            return "Default";
        }
    }
yanlusu commented 1 year ago

One of the solutions is to create several logger instances (if you know module names at compile time):

https://github.com/SergiusTheBest/plog/blob/0d9baad55cab98a7507d67d2d7934945da687a2b/samples/MultiInstance/Main.cpp#L8-L26

Thus you can control severity and turn on/off log messages per module name. Then you need to create a new formatter class and specify there a new field:

ss << PLOG_NSTR("[") << instanceIdToString(record.getInstanceId()) << PLOG_NSTR("] ");

and implement instanceIdToString. It could look like this:

    inline const char* instanceIdToString(int instanceId)
    {
        switch (instanceId)
        {
        case Auth:
            return "Auth;
        case FileIO:
            return "FileIO";
        default:
            return "Default";
        }
    }

good idea, thank you.