dynatrace-extensions / dt-extensions-python-sdk

Dynatrace Python Extensions SDK
https://dynatrace-extensions.github.io/dt-extensions-python-sdk/
MIT License
8 stars 2 forks source link

Set the extension logging level #43

Closed tyler-keyes7 closed 1 month ago

tyler-keyes7 commented 2 months ago

Request

In each extension I've developed, I end up copying over the same function to set the logging level of the Logger in the Extension class. It would be more convenient if this could be included in the Extension class.

Solution

Here is the python function I have been using, which gets defined as a class method in the "ExtensionImpl" class.

def set_logging_level(self, log_level: str = "INFO"):
    LOG_LEVEL = {
        "DEBUG": logging.DEBUG,
        "INFO": logging.INFO,
        "WARNING": logging.WARNING,
        "ERROR": logging.ERROR,
        "CRITICAL": logging.CRITICAL,
    }
    log_level = log_level.upper()
    if log_level not in LOG_LEVEL.keys():
        log_level = "INFO"
    print(f"setting log level to: {log_level}")
    self.logger.setLevel(LOG_LEVEL[log_level])

The "log_level" value gets set in the activation schema, typically using an enum of the possible log levels. However it is still good to check that the provided value is allowed.

JosephHobbs commented 2 months ago

Hello @tyler-keyes7! You mentioned using an enum to include possible log levels within the activation schema. Can you also provide an example of that? I'm having a heck of a time finding an example!

tyler-keyes7 commented 2 months ago

Sure! This log_level enum is usually what I use for extensions:

"enums": {
  "log_level": {
    "displayName": "Log level",
    "description": "",
    "documentation": "",
    "items": [
      {
        "value": "INFO",
        "displayName": "INFO"
      },
      {
        "value": "DEBUG",
        "displayName": "DEBUG"
      }
    ],
    "type": "enum"
  }
},

This enum can then be used as a property in another section:

"log_level": {
  "displayName": "Log level",
  "description": "Set the logging level of this extension on this host",
  "documentation": "",
  "type": {
    "$ref": "#/enums/log_level"
  },
  "nullable": false,
  "maxObjects": 1,
  "modificationPolicy": "DEFAULT",
  "default": "INFO"
}
JosephHobbs commented 2 months ago

Thank you!

dlopes7 commented 1 month ago

All of this code can be replaced with

level = self.config.get("log_level",  "INFO")
self.logger.setLevel(level)

I don't think we should add that much to the sdk, but it is probably a good idea to add the log_level attribute in the extension template so that folks use it as a good practice if they want.