Exemplo n.º 1
0
def test_json_exception(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    try:
        raise jsonlog.tests.records.ExampleException
    except jsonlog.tests.records.ExampleException:
        logging.exception("An exception occurred")
    assert '"traceback": ' in capture
Exemplo n.º 2
0
def test_json_args_map(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    logging.warning("%(action)s %(thing)s", {
        "action": "Hello",
        "thing": "World"
    })
    assert f"Hello World" in capture
Exemplo n.º 3
0
def test_json_error(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    try:
        raise jsonlog.tests.records.ExampleException
    except jsonlog.tests.records.ExampleException as exc_info:
        logging.error("An exception occurred", exc_info=exc_info)
    assert '"traceback": ' in capture
Exemplo n.º 4
0
def main(
    streams: typing.Iterable[typing.TextIO],
    config_path: str,
    log_path: str,
    pattern_name: str,
    level_key: typing.Optional[str],
    template: typing.Optional[str],
    _multiline_keys_add: typing.Sequence[str],
    _multiline_keys_replace: typing.Sequence[str],
    _priority_keys: typing.Sequence[str],
    _remove_keys: typing.Sequence[str],
) -> None:
    """Format line-delimited JSON log records in a human-readable way."""
    jsonlog.basicConfig(filename=ensure_log_path(log_path))

    remove_keys = Key.from_strings(_remove_keys)
    multiline_keys_add = Key.from_strings(_multiline_keys_add)
    multiline_keys_replace = Key.from_strings(_multiline_keys_replace)
    priority_keys = Key.from_strings(_priority_keys)

    streams = streams or (sys.stdin, )
    config: Config = Config.configure(config_path)
    pattern: Pattern = config.patterns[pattern_name]

    if level_key:
        pattern = pattern.replace(level_key=Key.from_string(level_key))

    if multiline_keys_replace:
        pattern = pattern.replace(multiline_keys=multiline_keys_replace)

    if multiline_keys_add:
        multiline_keys = (*pattern.multiline_keys, *multiline_keys_add)
        pattern = pattern.replace(multiline_keys=multiline_keys)

    if priority_keys:
        assert isinstance(pattern, KeyValuePattern)
        pattern = pattern.replace(priority_keys=priority_keys)

    if remove_keys:
        assert isinstance(pattern, KeyValuePattern)
        pattern = pattern.remove_keys(remove_keys)

    if template:
        assert isinstance(pattern, TemplatePattern)
        pattern = pattern.replace(template=template)

    for stream in streams:
        pattern.stream(stream)
Exemplo n.º 5
0
def test_adaptor(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    log = logging.getLogger(__name__)
    adaptor = logging.LoggerAdapter(log, {"hello": "world"})
    adaptor.warning("Message with extra attributes from an adaptor")
    assert '"hello": "world"' in capture
Exemplo n.º 6
0
def test_json_null(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    jsonlog.warning("No exc_info, traceback should be hidden")
    assert '"traceback": ' not in capture
Exemplo n.º 7
0
def test_json_extra(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    logging.warning("Hello world", extra={"key": "value"})
    assert '"key": "value"' in capture
Exemplo n.º 8
0
def test_json_args(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    logging.warning("%s %s", "Hello", "World")
    assert f"Hello World" in capture
Exemplo n.º 9
0
"""Attributes from a mapping passed as a lone positional argument are included."""

import jsonlog
import logging

jsonlog.basicConfig()
logging.warning("User clicked a button", {"user": 123})
Exemplo n.º 10
0
def test_basic_config_kwargs():
    with pytest.raises(ValueError):
        jsonlog.basicConfig(stream=sys.stderr, filename="test.log")
Exemplo n.º 11
0
def test_basic_config_filename():
    with tempfile.TemporaryDirectory() as tempdir:
        jsonlog.basicConfig(filename=pathlib.Path(tempdir) / "test.log")
Exemplo n.º 12
0
def test_already_configured():
    with pytest.warns(UserWarning):
        logging.basicConfig()
        jsonlog.basicConfig()
Exemplo n.º 13
0
def test_basic_config(capture: jsonlog.tests.capture.Capture):
    jsonlog.basicConfig()
    jsonlog.warning("Hello world")
    assert '"message": "Hello world"' in capture
Exemplo n.º 14
0
import logging
import sys

import jsonlog

jsonlog.basicConfig(level=jsonlog.DEBUG, stream=sys.stdout)

log = logging.getLogger("example")
log.debug("debug level log message")
log.info("info level log message")
log.warning("warning level log message")
log.error("error level log message")

try:
    1 / 0
except ZeroDivisionError:
    log.exception("error level log message with traceback")

log.critical("critical level log message")
Exemplo n.º 15
0
from collections import namedtuple
from cryptography import fernet
from aiohttp import web
from aiohttp_jwt import JWTMiddleware, check_permissions, match_any
from aiohttp_session import setup, get_session
from aiohttp_session.cookie_storage import EncryptedCookieStorage

_DEBUG_WEBSERVER_REQUESTS = True
_DEBUG_WEBSERVER_RESPONSES = True
_DEBUG_VERBOSE = True

jsonlog.basicConfig(
    level=jsonlog.INFO,
    indent=None,
    keys=("timestamp", "level", "message"),
    timespec="auto",
    #filename="{}/{}".format(os.path.realpath(os.path.dirname(os.path.abspath(__file__))),'access.log'),
    # filemode="a",
    # stream=None,
)

logging.warning("User clicked a button", extra={"user": 123})
"""
TRACE = 5
logging.addLevelName(TRACE, 'TRACE')
formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'})

logger.setLevel('TRACE')
logger.log(TRACE, 'a message using a custom level')
logger = logging.getLogger('example')
logger.addHandler(handler)
Exemplo n.º 16
0
def main():
    jsonlog.basicConfig()