Skip to content

Commit

Permalink
Fix JSON line logging (#3511)
Browse files Browse the repository at this point in the history
Co-authored-by: Jan Klopper <[email protected]>
  • Loading branch information
ammar92 and underdarknl authored Sep 17, 2024
1 parent daa7844 commit 6d0caeb
Show file tree
Hide file tree
Showing 14 changed files with 24 additions and 35 deletions.
3 changes: 1 addition & 2 deletions boefjes/boefjes/logging.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
"disable_existing_loggers": 0,
"formatters": {
"default": {
"format": "%(asctime)s [%(process)d] [%(levelname)s] [%(module)s] %(message)s",
"datefmt": "[%Y-%m-%d %H:%M:%S %z]"
"format": "%(message)s"
}
},
"handlers": {
Expand Down
3 changes: 1 addition & 2 deletions bytes/dev.logging.conf
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,4 @@ formatter=genericFormatter
kwargs={"stream": sys.stdout}

[formatter_genericFormatter]
format=%(asctime)s [%(process)d] [%(levelname)s] [%(module)s] %(message)s
datefmt=[%Y-%m-%d %H:%M:%S %z]
format=%(message)s
3 changes: 1 addition & 2 deletions bytes/logging.conf
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,4 @@ formatter=genericFormatter
kwargs={"stream": sys.stdout}

[formatter_genericFormatter]
format=%(asctime)s [%(process)d] [%(levelname)s] [%(module)s] %(message)s
datefmt=[%Y-%m-%d %H:%M:%S %z]
format=%(message)s
4 changes: 2 additions & 2 deletions octopoes/bits/definitions.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import importlib
import pkgutil
from functools import cache
from logging import getLogger
from pathlib import Path
from types import ModuleType

import structlog
from pydantic import BaseModel

from octopoes.models.types import OOIType

BITS_DIR = Path(__file__).parent
BIT_ATTR_NAME = "BIT"
logger = getLogger(__name__)
logger = structlog.get_logger(__name__)


class BitParameterDefinition(BaseModel):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
from collections.abc import Iterator
from typing import Any

Expand All @@ -10,8 +9,6 @@

LINK_SHORTENERS = link_shorteners_list()

logger = logging.getLogger(__name__)


def get_disallowed_hostnames_from_config(config, config_key, default):
disallowed_hostnames = config.get(config_key, None)
Expand Down
3 changes: 1 addition & 2 deletions octopoes/logging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ disable_existing_loggers: 0

formatters:
default:
format: "%(asctime)s [%(process)d] [%(levelname)s] [%(module)s] %(message)s"
datefmt: "[%Y-%m-%d %H:%M:%S %z]"
format: "%(message)s"

handlers:
console:
Expand Down
4 changes: 2 additions & 2 deletions octopoes/octopoes/api/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from collections import Counter
from collections.abc import Generator
from datetime import datetime
from logging import getLogger
from operator import itemgetter
from typing import Any, Literal

import structlog
from asgiref.sync import sync_to_async
from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Request, status
from httpx import HTTPError
Expand Down Expand Up @@ -41,7 +41,7 @@
from octopoes.xtdb.query import Aliased
from octopoes.xtdb.query import Query as XTDBQuery

logger = getLogger(__name__)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix="/{client}")


Expand Down
11 changes: 7 additions & 4 deletions octopoes/octopoes/connector/octopoes.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from octopoes.models.transaction import TransactionRecord
from octopoes.models.tree import ReferenceTree
from octopoes.models.types import OOIType
from octopoes.types import DECLARATION_CREATED, OBJECT_DELETED, OBSERVATION_CREATED, ORIGIN_DELETED


class OctopoesAPIConnector:
Expand Down Expand Up @@ -176,14 +177,16 @@ def delete_origin(self, origin_id: str, valid_time: datetime) -> None:

self.session.delete(f"/{self.client}/origins", params=params)

self.logger.info("Deleted origin", origin_id=origin_id, valid_time=valid_time, event_code=ORIGIN_DELETED)

def save_observation(self, observation: Observation) -> None:
self.session.post(
f"/{self.client}/observations",
headers={"Content-Type": "application/json"},
content=observation.model_dump_json(),
)

self.logger.info("Saved observation", observation=observation)
self.logger.info("Saved observation", observation=observation, event_code=OBSERVATION_CREATED)

def save_declaration(self, declaration: Declaration) -> None:
self.session.post(
Expand All @@ -192,7 +195,7 @@ def save_declaration(self, declaration: Declaration) -> None:
content=declaration.model_dump_json(),
)

self.logger.info("Saved declaration", declaration=declaration)
self.logger.info("Saved declaration", declaration=declaration, event_code=DECLARATION_CREATED)

def save_affirmation(self, affirmation: Affirmation) -> None:
self.session.post(
Expand All @@ -201,7 +204,7 @@ def save_affirmation(self, affirmation: Affirmation) -> None:
content=affirmation.model_dump_json(),
)

self.logger.info("Saved affirmation", affirmation=affirmation)
self.logger.info("Saved affirmation", affirmation=affirmation, event_code=DECLARATION_CREATED)

def save_scan_profile(self, scan_profile: ScanProfile, valid_time: datetime):
params = {"valid_time": str(valid_time)}
Expand All @@ -224,7 +227,7 @@ def delete(self, reference: Reference, valid_time: datetime) -> None:
params = {"reference": str(reference), "valid_time": str(valid_time)}
self.session.delete(f"/{self.client}/", params=params)

self.logger.info("Deleted object", reference=reference, valid_time=valid_time)
self.logger.info("Deleted object", reference=reference, valid_time=valid_time, event_code=OBJECT_DELETED)

def delete_many(self, references: list[Reference], valid_time: datetime) -> None:
params = {"valid_time": str(valid_time)}
Expand Down
4 changes: 2 additions & 2 deletions octopoes/octopoes/core/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from collections import Counter
from collections.abc import Callable, ValuesView
from datetime import datetime, timezone
from logging import getLogger
from time import perf_counter
from typing import Literal, overload

import structlog
from bits.definitions import get_bit_definitions
from bits.runner import BitRunner
from pydantic import TypeAdapter
Expand Down Expand Up @@ -47,7 +47,7 @@
from octopoes.repositories.scan_profile_repository import ScanProfileRepository
from octopoes.xtdb.client import Operation, OperationType, XTDBSession

logger = getLogger(__name__)
logger = structlog.get_logger("octopoes-core-service")
settings = Settings()


Expand Down
3 changes: 0 additions & 3 deletions octopoes/octopoes/repositories/origin_parameter_repository.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from datetime import datetime
from http import HTTPStatus
from logging import getLogger
from typing import Any

from httpx import HTTPStatusError
Expand All @@ -16,8 +15,6 @@
from octopoes.xtdb.client import XTDBSession
from octopoes.xtdb.query_builder import generate_pull_query

logger = getLogger(__name__)


class OriginParameterRepository(Repository):
def __init__(self, event_manager: EventManager):
Expand Down
3 changes: 0 additions & 3 deletions octopoes/octopoes/repositories/origin_repository.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from datetime import datetime
from http import HTTPStatus
from logging import getLogger
from typing import Any
from uuid import UUID

Expand All @@ -17,8 +16,6 @@
from octopoes.xtdb.client import XTDBSession
from octopoes.xtdb.query_builder import generate_pull_query

logger = getLogger(__name__)


class OriginRepository(Repository):
def __init__(self, event_manager: EventManager):
Expand Down
3 changes: 0 additions & 3 deletions octopoes/octopoes/repositories/scan_profile_repository.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from datetime import datetime
from http import HTTPStatus
from logging import getLogger
from typing import Any

from httpx import HTTPStatusError
Expand All @@ -16,8 +15,6 @@
from octopoes.xtdb.client import XTDBSession
from octopoes.xtdb.query_builder import generate_pull_query

logger = getLogger(__name__)


class ScanProfileRepository(Repository):
def __init__(self, event_manager: EventManager):
Expand Down
6 changes: 6 additions & 0 deletions octopoes/octopoes/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Event codes for certain actions
OBSERVATION_CREATED = 100101
DECLARATION_CREATED = 100201
AFFIRMATION_CREATED = 100301
ORIGIN_DELETED = 100403
OBJECT_DELETED = 100503
6 changes: 1 addition & 5 deletions rocky/rocky/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,11 +527,7 @@ def immutable_file_test(path, url):
structlog.dev.set_exc_info,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper("iso", utc=False),
(
structlog.processors.JSONRenderer()
if LOGGING_FORMAT == "json"
else structlog.dev.ConsoleRenderer(colors=True, pad_level=False)
),
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
],
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
Expand Down

0 comments on commit 6d0caeb

Please sign in to comment.