{time:YYYY-MM-DD HH:mm:ss" /> {time:YYYY-MM-DD HH:mm:ss" /> {time:YYYY-MM-DD HH:mm:ss"/>

How to set time zone in loguru?

160 Views Asked by At

How can i set time zone Tashkent (UTC+5) to this code

from loguru import logger as lg

def setup_logger():
    format = (
        "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
        "<level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
        "<level>{message}</level>"
    )
    lg.add("logs/debug.log", format=format,
           level="DEBUG", rotation="1 week", compression="zip")

I looked through the entire Internet, but can't find. Please help!

I tried pendulum, datetime and other things. I think it will be real with "record" in loguru, but i can't.

1

There are 1 best solutions below

0
Matt Johnson-Pint On

If you are running on Linux, macOS, or another OS that supports IANA time zones directly (ie. not Windows), you should be able to set the TZ environment variable before your app starts.

export TZ=Asia/Tashkent
python app.py

Or, you can do it within the app like this:

import os, time
os.environ['TZ'] = 'Asia/Tashkent'
time.tzset()

Alternatively, you can adapt the approach from this github issue to update the record used in loguru:

def set_datetime(record):
    dt = datetime.datetime.now(ZoneInfo("Asia/Tashkent"))
    record["extra"]["datetime"] = dt

logger.configure(patcher=set_datetime)
logger.add(sys.stderr, format="{extra[datetime]} {message}")

This requires Python 3.9+ to use ZoneInfo to get the current time in a specific time zone. If needed, you can use pendulum, arrow, or pytz in older Python.