SCM-NV / PLAMS

Python Library for Automating Molecular Simulations
https://www.scm.com/doc/plams
Other
65 stars 24 forks source link

Use standard logger in log function #158

Open dormrod opened 2 weeks ago

dormrod commented 2 weeks ago

Description

We are currently considering how to improve the PLAMS logging for a better user experience.

This includes having logging of job summaries etc. as in https://github.com/SCM-NV/PLAMS/pull/156

As a first step though, a refactor of the existing log method in PLAMS. This currently had it's own logging implementation to write to stdout and a file, including handling the thread safety etc.

This change maintains the current behaviour exactly, but instead uses the standard python logger and formatter etc. This is more a best-practice change at the moment, but also provides a pattern for adding other logger types.

Implementation

A wrapper class Logger has been added to scm.plams.core.logging. It is a thin wrapper over the standard library logger, which has an interface optimised for the current usage in PLAMS. It has a configure method and a log method which are both used by the general log function.

Note that the configure methods are called very frequently (every time log is called), but they only update the handlers if there is an actual change to the config. This is required as the current behaviour is to log to the global config default job manger, which can be changed dynamically in the script. So this can't be a one-time-setup type of configuration.

Instead of instantiating the Logger directly, a LogManager static class has also been added. This allows the loggers to be accessed by name and makes sure they are singletons. This is exposed to the user via a get_logger helper method.

Example

An example usage is as follows:

Screenshot 2024-10-18 at 10 02 46

Testing

Logging tests were added for log function, which passed before and after this change.

Specific tests have also been added for the Logger class.

In addition, the scripting tests for PLAMS were run, which should flag any issues as the diffs would be incorrect

Future Extensions

It would now be possible to add a get_csv_logger method which could return a csv logger based on a similar pattern to the current logger. There could also be an (abstract) base class for the different logger types.