0

From reading the docs about logging, I know I can use the basicConfig for example to set the format of logging records, such as:

import logging

logging.basicConfig(format="%(levelname)s - %(message)s")

for example.

My question is, can I specify different formats for different levels? What I'm trying to achieve is to format logging records to Azure Pipelines logging commands so that for examle the Python code:

logging.error("some error")

Will be printed as:

##[error]some error

Now I know I can use the %(levelname) but I don't want to rely on the correspondence between Azure Pipelines logging commands to Python's "logging" module. For example, in Python's logging there's info level, but not in Azure Pipelines.

YoavKlein
  • 2,005
  • 9
  • 38
  • There might be an alternate avenue: does the Python logging module allow you to specify custom log levels? It's mentioned that it's possible [here](https://docs.python.org/3.9/howto/logging.html#custom-levels) but with no further elaboration on how to do so – Alexander Oct 23 '21 at 22:30
  • I think the best way to achieve this is building your own wrapper class above the **logging** module. A similar approach was suggested [here](https://stackoverflow.com/questions/1343227/can-pythons-logging-format-be-modified-depending-on-the-message-log-level/8349076). – pyhalex Oct 23 '21 at 22:21

1 Answers1

0

There's an Azure doc specifically for Python logging which you might find useful. If I understand it correctly (I've never used Azure), you should be able to send it Python logs without doing anything special.

However, the log messages shown as part of this Azure chart are plainly a bit different. If you want your messages to appear like that, one option is to set some custom levels with the level-names Azure prefers. The doc you referenced has a section on that, although it warns against doing it in complex libraries.

If you want to reuse standard levels, but rename "info" -> "command" or some such, you're probably going to need a separate formatter for each such rename.

Sarah Messer
  • 3,592
  • 1
  • 26
  • 43