{"id":9901,"library":"logging-json","title":"logging-json","description":"logging-json is a Python library that provides a JSON formatter for the standard `logging` module, allowing applications to output logs in a structured JSON format. This is particularly useful for centralized logging systems and machine readability. The current version is 0.6.0, and it generally maintains an active release cadence with periodic updates for bug fixes and new features.","status":"active","version":"0.6.0","language":"en","source_language":"en","source_url":"https://github.com/thibaud-zani/logging-json","tags":["logging","json","formatter","logs","structured-logging"],"install":[{"cmd":"pip install logging-json","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for timezone-aware datetime formatting in log entries.","package":"tzlocal","optional":false}],"imports":[{"symbol":"JSONFormatter","correct":"from logging_json import JSONFormatter"}],"quickstart":{"code":"import logging\nfrom logging_json import JSONFormatter\nimport sys\n\n# Configure a logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# Create a stream handler (e.g., to stdout)\nhandler = logging.StreamHandler(sys.stdout)\n\n# Create a JSON formatter instance\n# Optional: Customize indentation, ASCII encoding, or datetime format\nformatter = JSONFormatter(\n    json_indent=2, # Pretty-print JSON\n    json_ensure_ascii=False, # Allow non-ASCII characters directly\n    datetime_format=\"%Y-%m-%dT%H:%M:%S%z\" # Custom datetime format with timezone\n)\n\n# Set the formatter for the handler\nhandler.setFormatter(formatter)\n\n# Add the handler to the logger\nlogger.addHandler(handler)\n\n# Log messages with standard fields and extra context\nlogger.info(\"This is an info message.\")\nlogger.warning(\"Something potentially bad happened.\", extra={\"user_id\": 123, \"session\": \"abc\"})\n\ntry:\n    raise ValueError(\"Example error\")\nexcept ValueError:\n    # logger.exception automatically includes traceback\n    logger.exception(\"An error occurred during processing.\")\n\nlogger.debug(\"This message will not be shown as level is INFO.\")","lang":"python","description":"This quickstart demonstrates how to set up a basic logger with `logging-json`. It configures a `StreamHandler` to output JSON formatted logs to standard output. It also shows how to include extra dictionary fields in your logs, which are automatically merged into the root JSON object."},"warnings":[{"fix":"Ensure your project's Python interpreter is at least 3.9. If you need to support older Python versions, you must pin `logging-json` to a version prior to 0.5.0 (e.g., `logging-json<0.5`).","message":"Versions 0.5.0 and later of `logging-json` require Python 3.9 or higher. Previous versions supported Python 3.7+.","severity":"breaking","affected_versions":"0.5.0+"},{"fix":"Always pass JSON-serializable types (strings, numbers, booleans, lists, dicts) in `extra`. For complex objects, convert them to a serializable representation (e.g., `str(obj)` or `obj.to_dict()`) before passing them, or implement a custom JSON encoder within `JSONFormatter`.","message":"The `extra` dictionary passed to logging calls is merged directly into the top-level JSON object. Ensure values within `extra` are JSON-serializable or expect them to be stringified by default. Complex objects (e.g., custom classes) can lead to serialization errors if not handled.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Instead of `logging.basicConfig()`, create and configure `logging.StreamHandler` or `logging.FileHandler` instances, create a `JSONFormatter`, and then explicitly attach the formatter to the handler using `handler.setFormatter(formatter)` and the handler to the logger using `logger.addHandler(handler)`.","message":"Directly using `logging.basicConfig()` with `logging-json` can be tricky as `basicConfig` doesn't easily allow setting a custom formatter with specific parameters beyond a basic format string. You often need to manually configure handlers.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Before logging, convert the object to a basic JSON-serializable type (e.g., `str(obj)`, `list(obj_set)`, `obj.to_dict()`). Alternatively, for more advanced cases, you can provide a custom `json_encoder` argument to `JSONFormatter` to handle specific types.","cause":"You are attempting to log an object of a custom type or a non-standard Python type (e.g., a `set`) directly in your log message or within the `extra` dictionary, and the default JSON encoder does not know how to serialize it.","error":"TypeError: Object of type <YourCustomType> is not JSON serializable"},{"fix":"Verify that `handler.setFormatter(json_formatter)` was called with your `JSONFormatter` instance and that `logger.addHandler(handler)` was called for each logger you intend to use. Avoid using `logging.basicConfig()` after custom handler setup, or ensure your `basicConfig` setup explicitly configures the desired handler and formatter.","cause":"The `JSONFormatter` was either not correctly assigned to a handler, or the handler with the `JSONFormatter` was not added to the logger instance. This can also happen if `basicConfig` overrides custom handler setup.","error":"Logs are not appearing in JSON format, or default Python log format is shown."},{"fix":"Upgrade `logging-json` to version 0.6.0 or higher, which includes fixes for how `extra` fields are handled. Always ensure the values in your `extra` dictionary are fundamentally JSON-serializable (strings, numbers, lists, etc.) to prevent such issues.","cause":"In older versions (prior to 0.6.0), there were specific bugs related to how `extra` dictionary values were processed, particularly when they were complex objects or dictionaries themselves. This could lead to unexpected `AttributeError` when the formatter tried to apply `str()` to an already-dict-like object.","error":"AttributeError: 'dict' object has no attribute 'str' (or similar error related to extra fields)"}]}