Start using this library¶
Install into your project¶
Requires¶
ssh key added in your github account
add it here (you will need to copy-paste the content of your public key)
Install¶
pip install git+ssh://git@github.com/B2Gov/logger.git@[BRANCH_OR_TAG]
If @[BRANCH_OR_TAG] is not used, it will use the main or
master branch of that repository.
Declare as dependency¶
At setup.cfg
[options]
install_requires =
logger-b2gov @ git+ssh://git@github.com/B2Gov/logger.git@[BRANCH_OR_TAG]
Further reading: (stackoverflow) install_requires for private repos
Log wrapper¶
You could make a class that inherits from LogWrapper which
will give to your class the attribute logger, and
automatically can log anything you want.
For example, we will save this code in a file called mycode.py:
from logger import LogWrapper
class MyAwesomeClass(LogWrapper):
def __init__(self):
super().__init__(
__name__
)
def mymethod(self):
x = 5
self.logger.info(f"The value of x is {x}")
def main():
MyAwesomeClass().mymethod()
if __name__ == "__main__":
main()
If we run this code, the output looks something like this:
2021-09-24 09:23:28,748 [__main__][INFO] The value of x is 5
If we import this code from another module, we will see that __name__ changes. For example, let’s add another file in the same directory called test.py with this script:
import mycode
mycode.MyAwesomeClass().mymethod()
And run it:
2021-09-24 09:24:09,863 [mycode][INFO] The value of x is 5
Now, we can see the name of mycode in the tag. (More of __name__)
You can change the logger format by calling the
make_new_logger() method. For example, let’s replace
our code in test.py with this script:
import mycode
myobject = mycode.MyAwesomeClass()
myobject.mymethod()
myobject.make_new_logger(
myobject.__module__,
extra_fields={ # Optional!
'ocid': 'ocds-abc123-id123',
'important-tag': 'hello!'
}
)
myobject.mymethod()
Run it:
2021-09-24 09:24:50,042 [mycode][INFO] The value of x is 5
2021-09-24 09:24:50,042 [mycode][ocds-abc123-id123][hello!][INFO] The value of x is 5