Loguru: Fastapi logging

Created on 13 Aug 2020  路  6Comments  路  Source: Delgan/loguru

How can I log a request with his params and headers ?. Something like this:

INFO 2020-08-13 13:36:33.494 uvicorn.protocols.http.h11_impl:send - 127.0.0.1:52660 - "GET /url1/url2/ HTTP/1.1" 400 params= {"some": value, "some1":value} headers={"header1": value}

I'm using loguru with fastapi and uvicorn.

question

Most helpful comment

That happens because of colorize=True. Loguru will add ansi codes to colorize your logs. However, these codes are only transformed to colors while inside a terminal.

By default, if the colorize argument is not provided, Loguru tries to guess whether or not the sink (like sys.stderr or a file) supports ansi codes and strip them out if it doesn't. However as you specified colorize=True, Loguru will add them anyway. That's why you're seeing such symbols in your file.

You can set colorize=False or just plainly omit this parameter and it should work fine. :wink:

All 6 comments

Hi @lvar, I saw your comment here: https://github.com/tiangolo/fastapi/issues/1276#issuecomment-673893420

So I assume you figured out a solution to get fastapi logs propagated to loguru.

About your new problem of sending payload to the file: I think {extra} is missing in the format of your handler. The extra record's attribute is a basic dict to which parameters passed to bind() are added. If you don't specify a format while adding a loguru handler, the extra parameters will not appear in the output (because the default format does not use it). Example:

logger.add("file.log", format="{time} - {message} - {extra[payload]}"
logger.configure(extra={"payload": None})  # Default value
logger.bind(payload=await request.json()).debug("params with formating")

@Delgan thanks for trying to help me. About your suggestion, I don't know if you saw the proposed solution in fastapi thread.

https://gist.github.com/Slyfoxy/a3e31cfcc1b19cba8e1b626276148c49

That's what I'm trying to implement...and I think the code already have a function that uses the payload in format, but for some reason does'nt show on log file...this is the function:

def format_record(record: dict) -> str:
  format_string = LOGURU_FORMAT
     if record["extra"].get("payload") is not None:
        record["extra"]["payload"] = pformat(
        record["extra"]["payload"], indent=4, compact=True, width=88
     )
    format_string += "\n<level>{extra[payload]}</level>"

   format_string += "{exception}\n"
   return format_string

Thanks again for your help and please excuse my english

Indeed, but look at where the format_record is used in the snippet you shared:

logger.configure(
    handlers=[{"sink": sys.stdout, "level": logging.DEBUG, "format": format_record}]
)

This custom format is only used to configure the sys.stdout handler. If you want the same format for the logs emitted to your file, you need to specify it while adding the file handler too. For example:

logger.add("log/access.log", format=format_record, enqueue=True , backtrace=True, diagnose=True)

Working now !! thank you !! I really appreciate the time you take...

now I'm facing a little issue, don't know why it's happening
Screenshot_1

Why format look like that ? I'm using this:

logger.add("log/access.log",backtrace=True, colorize=True, level="DEBUG", format="<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>")

That happens because of colorize=True. Loguru will add ansi codes to colorize your logs. However, these codes are only transformed to colors while inside a terminal.

By default, if the colorize argument is not provided, Loguru tries to guess whether or not the sink (like sys.stderr or a file) supports ansi codes and strip them out if it doesn't. However as you specified colorize=True, Loguru will add them anyway. That's why you're seeing such symbols in your file.

You can set colorize=False or just plainly omit this parameter and it should work fine. :wink:

I'm closing this issue since I think the problem is fixed now. Otherwise, feel free to re-open it. ;)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yoonghm picture yoonghm  路  3Comments

flybaozi picture flybaozi  路  4Comments

BarryThrill picture BarryThrill  路  6Comments

zhouxiaomao picture zhouxiaomao  路  6Comments

AllanLRH picture AllanLRH  路  6Comments