1

I'm using the loguru package for logging in my python project.

https://github.com/Delgan/loguru

I'm looking to override the default format so I can specify a fixed with for the module / function / line number string.

Here's the default format ...

'<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>'

The output is something like this ...

2020-12-28 14:36:27.510 | INFO     | package1.module1:function:132 - Listing Users...
2020-12-28 14:36:27.601 | ERROR    | package10.module10:function10:1000 - The provided token has expired

I want to add a static width/padding to the package/module/function so the output looks like ...

2020-12-28 14:36:27.510 | INFO     | package1.module1:function:132      - Listing Users...
2020-12-28 14:36:27.601 | ERROR    | package10.module10:function10:1000 - The provided token has expired

The problem is the full path with function line number is constructed from 3 variables ...

<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>

Is there any way I can specify a width for the combination of the strings? Something like ...

<cyan>{name + ":" + function + ":" + line : 45}</cyan>

Appreciate the help!

1
  • 1
    The {level: <8} part does this; you can do {name + ":" + function + ":" + line: <45} just the same way. Commented Dec 28, 2020 at 23:44

1 Answer 1

1

You can always limit string length, just like you would do with any sequence:

# 150 chars string:
x = "abc" * 50

# 30 chars string:
y = "xyz" * 10

# predefined display limit:
n = 45

spaces = " " * n
print(f"{(x+spaces)[:n]} end line")
print(f"{(y+spaces)[:n]} end line")
print(f"{(y+x+spaces)[:n]} end line")

Outputs:

abcabcabcabcabcabcabcabcabcabcabcabcabcabcabc end line
xyzxyzxyzxyzxyzxyzxyzxyzxyzxyz                end line
xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzabcabcabcabcabc end line
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, sadly that doesn't align the string to the right of 'x' and 'y'. The desired output would have "end line" aligned
@TylerWeiss - have a look now - this should do the trick (you may want to pack the whole thing in a function for code clarity)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.