0

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!

Tyler Weiss
  • 139
  • 1
  • 15
  • 1
    The `{level: <8}` part does this; you can do `{name + ":" + function + ":" + line: <45}` just the same way. – kaya3 Dec 28 '20 at 23:44

1 Answers1

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
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • 1
    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 – Tyler Weiss Dec 28 '20 at 23:06
  • @TylerWeiss - have a look now - this should do the trick (you may want to pack the whole thing in a function for code clarity) – Grzegorz Skibinski Dec 28 '20 at 23:20