Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include Native Log Record Attributes #2

Closed
jteppinette opened this issue Feb 13, 2022 · 1 comment
Closed

Include Native Log Record Attributes #2

jteppinette opened this issue Feb 13, 2022 · 1 comment
Assignees

Comments

@jteppinette
Copy link
Owner

We should be able to configure the logger to always include some default keys. For example, a user may want to always include a time or logger key.

This functionality is seen in the python-json-logger.

@jteppinette jteppinette self-assigned this Feb 13, 2022
@jteppinette jteppinette changed the title Add Additional Keys Include Native Log Record Attributes Apr 20, 2022
@jteppinette
Copy link
Owner Author

This functionality has been added by the latest 0.0.5 release.


Default Keys

You can request that the formatter always include certain attributes on the
log record by using the keys parameter. If the key you want to include in
your output is represented by a different attribute on the log record, then
you can use the mapping parameter to provide that key/attribute mapping.

Notice, the keys parameter defaults to ["at"] and will be overridden
by any provided keys.

import logging
from logfmter import Logfmter

formatter = Logfmter(keys=["at", "processName"])

handler = logging.StreamHandler()
handler.setFormatter(formatter)

logging.basicConfig(handlers=[handler])

logging.error("hello") # at=ERROR processName=MainProceess msg=hello

Utilizing a mapping to convert the processName attribute to process.

Notice, the mapping parameter defaults to {"at": "levelname"} and will be overridden
by any provided mapping.

import logging
from logfmter import Logfmter

formatter = Logfmter(
    keys=["at", "process"],
    mapping={"at": "levelname", "process": "processName"}
)

handler = logging.StreamHandler()
handler.setFormatter(formatter)

logging.basicConfig(handlers=[handler])

logging.error("hello") # at=ERROR process=MainProceess msg=hello

Date Formatting

If you request the asctime attribute (directly or through a mapping), then the date format
can be overridden through the datefmt parameter.

import logging
from logfmter import Logfmter

formatter = Logfmter(
    keys=["at", "when"],
    mapping={"at": "levelname", "when": "asctime"},
    datefmt="%Y-%m-%d"
)

handler = logging.StreamHandler()
handler.setFormatter(formatter)

logging.basicConfig(handlers=[handler])

logging.error("hello") # at=ERROR when=2022-04-20 msg=hello

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant