Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Serializer formater, use of included log formatter #855

Closed
ch0wm3in opened this issue Apr 26, 2023 · 3 comments
Closed

Custom Serializer formater, use of included log formatter #855

ch0wm3in opened this issue Apr 26, 2023 · 3 comments
Labels
enhancement Improvement to an already existing feature

Comments

@ch0wm3in
Copy link

Hi,

Consider the following

def serialize(record):
    """Serialize the JSON log.
    """
    log = {}
    log["time"] = record["time"].timestamp()
    log["level"] = record["level"].name
    log["message"] = record["message"]
    log["func_string"] = f"{record['name']}:{record['function']}:{record['line']}"
    log["correlation_id"] = call_uuid
    log["total_runtime"] = record["elapsed"].seconds


    if record["exception"] is not None:
        error_data = {
            "error": {
                "stack": "".join(
                    traceback.format_exception(
                        record["exception"].type,
                        record["exception"].value,
                        record["exception"].traceback,
                    )
                ),
                "kind": getattr(record["exception"].type, "__name__", "None"),
                "message": str(record["exception"].value),
            },
        }
        log.update(error_data)
    
    return json.dumps(log, ensure_ascii=False)

How would i go about using the time format of "{time:YYYY-MM-DDTHH:mm:ss.SSSSSSSSSZ}" in a json serializer for the log["time"]? I see that record["time"] a datetime object, python datetime does not support nanoseconds afaik, but above works fine with stderr sink. Is there a way to set default time format globally across all sinks using the time formatter that's included in the libary?

@ch0wm3in ch0wm3in changed the title Serializer formater, use of text format Custom Serializer formater, use of included log formatter Apr 26, 2023
@Delgan
Copy link
Owner

Delgan commented Apr 26, 2023

Hi.

Loguru does not support nanosecond neither.
When you use "SSSSSSSSS" in the format, it's certainly parsed as "SSSSSS" concatenated with "SSS". Basically, microseconds joined with milliseconds, that give the impression of being nanoseconds.

Maybe should I detect this pattern and raise an exception?

Anyway, if you need nanoseconds in your JSON serializer, you can use a patch function:

def add_nanoseconds(record):
    record["extra"]["nanoseconds"] = time.time_ns()

logger.configure(patcher=add_nanoseconds)

Then you can access record["extra"]["nanoseconds"] each time a message is logged.

@ch0wm3in
Copy link
Author

Oh okay, yeah i would like an exception or at least a notion of that it's not actually nanoseconds 😁

Thanks for the supplied, i ended up accepting using rfc3339micro instead of nano with pendulum doing the following in my serializer:

import pendulum

def serialize(record):
    """Serialize the JSON log.
    """
    dt = pendulum.instance(record["time"])
    log = {}
    log["log_time"] = dt.format("YYYY-MM-DDTHH:mm:ss.SSSSSSZ")
    log["level"] = record["level"].name
    log["message"] = record["message"]
    log["func_string"] = f"{record['name']}:{record['function']}:{record['line']}"
    log["correlation_id"] = call_uuid
    log["total_runtime"] = record["elapsed"].seconds
    log["script_name"] = record["extra"].get("script_name", "")


    if record["exception"] is not None:
        error_data = {
            "error": {
                "stack": "".join(
                    traceback.format_exception(
                        record["exception"].type,
                        record["exception"].value,
                        record["exception"].traceback,
                    )
                ),
                "kind": getattr(record["exception"].type, "__name__", "None"),
                "message": str(record["exception"].value),
            },
        }
        log.update(error_data)

@Delgan
Copy link
Owner

Delgan commented Apr 28, 2023

Indeed, using pendulum would have been my suggestion, since Loguru implements the same formatting rules. 👍

I keep this ticket open and I'll try to detect pattern with more than 6 successive "S" and raise an exception in that case.

@Delgan Delgan added the enhancement Improvement to an already existing feature label Apr 28, 2023
@Delgan Delgan closed this as completed Apr 28, 2023
jmctune pushed a commit to dqx-translation-project/dqxclarity that referenced this issue Oct 9, 2023
[![Mend
Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| [loguru](https://togithub.com/Delgan/loguru)
([changelog](https://togithub.com/Delgan/loguru/blob/master/CHANGELOG.rst))
| `==0.7.0` -> `==0.7.2` |
[![age](https://developer.mend.io/api/mc/badges/age/pypi/loguru/0.7.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/pypi/loguru/0.7.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/pypi/loguru/0.7.0/0.7.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/loguru/0.7.0/0.7.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>Delgan/loguru (loguru)</summary>

###
[`v0.7.2`](https://togithub.com/Delgan/loguru/blob/HEAD/CHANGELOG.rst#072-2023-09-11)

[Compare
Source](https://togithub.com/Delgan/loguru/compare/0.7.1...0.7.2)

\=====================

- Add support for formatting of `ExceptionGroup` errors (`#&#8203;805
<https://github.com/Delgan/loguru/issues/805>`\_).
- Fix possible `RuntimeError` when using
`multiprocessing.set_start_method()` after importing the `logger`
(`#&#8203;974 <https://github.com/Delgan/loguru/issues/974>`\_)
- Fix formatting of possible `__notes__` attached to an `Exception`
(`#&#8203;980 <https://github.com/Delgan/loguru/issues/980>`\_).

###
[`v0.7.1`](https://togithub.com/Delgan/loguru/blob/HEAD/CHANGELOG.rst#071-2023-09-04)

[Compare
Source](https://togithub.com/Delgan/loguru/compare/0.7.0...0.7.1)

\=====================

- Add a new `context` optional argument to `logger.add()` specifying
`multiprocessing` context (like `"spawn"` or `"fork"`) to be used
internally instead of the default one (`#&#8203;851
<https://github.com/Delgan/loguru/issues/851>`\_).
- Add support for true colors on Windows using ANSI/VT console when
available (`#&#8203;934 <https://github.com/Delgan/loguru/issues/934>`*,
thanks `@tunaflsh <https://github.com/tunaflsh>`*).
- Fix possible deadlock when calling `logger.complete()` with concurrent
logging of an asynchronous sink (`#&#8203;906
<https://github.com/Delgan/loguru/issues/906>`\_).
- Fix file possibly rotating too early or too late when re-starting an
application around midnight (`#&#8203;894
<https://github.com/Delgan/loguru/issues/894>`\_).
- Fix inverted `"<hide>"` and `"<strike>"` color tags (`#&#8203;943
<https://github.com/Delgan/loguru/pull/943>`*, thanks `@tunaflsh
<https://github.com/tunaflsh>`*).
- Fix possible untraceable errors raised when logging non-unpicklable
`Exception` instances while using `enqueue=True` (`#&#8203;329
<https://github.com/Delgan/loguru/issues/329>`\_).
- Fix possible errors raised when logging non-picklable `Exception`
instances while using `enqueue=True` (`#&#8203;342
<https://github.com/Delgan/loguru/issues/342>`*, thanks `@ncoudene
<https://github.com/ncoudene>`*).
- Fix missing seconds and microseconds when formatting timezone offset
that requires such accuracy (`#&#8203;961
<https://github.com/Delgan/loguru/issues/961>`\_).
- Raise `ValueError` if an attempt to use nanosecond precision for time
formatting is detected (`#&#8203;855
<https://github.com/Delgan/loguru/issues/855>`\_).

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined),
Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://www.mend.io/free-developer-tools/renovate/). View
repository job log
[here](https://developer.mend.io/github/dqx-translation-project/dqxclarity).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjMiLCJ1cGRhdGVkSW5WZXIiOiIzNy44LjEiLCJ0YXJnZXRCcmFuY2giOiJtYWluIn0=-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Improvement to an already existing feature
Projects
None yet
Development

No branches or pull requests

2 participants