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

Fixed logging not being sent to console. #22

Merged
merged 1 commit into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Added

- Added `HOST` and `PORT` settings to allow overriding the host and port of the service.
- Added `LOG_LEVEL` setting to allow overriding the log level of the service.

### Fixed

- Fixed logging configuration for `daiv_sandbox` logger, no logs where being written to the console.
- Fixed `SENTRY_ENABLE_TRACING` setting to be a boolean or an integer.

## [0.1.0-rc.7] - 2024-12-16

### Added
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
&& adduser app docker

ENV PATH="/home/app/.venv/bin:$PATH"
ENV PYTHONPATH="$PYTHONPATH:/home/app/daiv_sandbox/"

Check warning on line 58 in Dockerfile

View workflow job for this annotation

GitHub Actions / docker

Variables should be defined before their use

UndefinedVar: Usage of undefined variable '$PYTHONPATH' More info: https://docs.docker.com/go/dockerfile/rule/undefined-var/
ENV PYTHONUNBUFFERED=1

# Copy python compiled requirements
Expand All @@ -74,4 +74,4 @@

EXPOSE 8000

CMD ["fastapi", "run", "daiv_sandbox/main.py", "--host", "0.0.0.0", "--port", "8000"]
CMD ["python", "daiv_sandbox/main.py"]
17 changes: 12 additions & 5 deletions daiv_sandbox/config.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
from typing import Literal

from pydantic import HttpUrl
from pydantic import Field, HttpUrl
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
model_config = SettingsConfigDict(secrets_dir="/run/secrets", env_prefix="DAIV_SANDBOX_")
model_config = SettingsConfigDict(secrets_dir="/run/secrets", env_prefix="DAIV_SANDBOX_", env_ignore_empty=True)

# Server
HOST: str = "0.0.0.0" # noqa: S104
PORT: int = 8000

# Environment
ENVIRONMENT: Literal["local", "staging", "production"] = "local"
ENVIRONMENT: Literal["local", "production"] = "production"

# Logging
LOG_LEVEL: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"

# API
API_V1_STR: str = "/api/v1"
API_KEY: str

# Sentry
SENTRY_DSN: HttpUrl | None = None
SENTRY_ENABLE_TRACING: bool = False
SENTRY_ENABLE_TRACING: bool | int = False

# Execution
MAX_EXECUTION_TIME: int = 600 # seconds
RUNTIME: Literal["runc", "runsc"] = "runc"
KEEP_TEMPLATE: bool = False
MAX_EXECUTION_TIME: int = Field(default=600, description="Maximum execution time in seconds")


settings = Settings() # type: ignore
17 changes: 17 additions & 0 deletions daiv_sandbox/logs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from fastapi_cli.utils.cli import get_uvicorn_log_config # noqa: A005

from daiv_sandbox.config import settings

# Configure logger

LOGGING_CONFIG = get_uvicorn_log_config()
LOGGING_CONFIG["formatters"]["verbose"] = {
"format": "[%(asctime)s] %(levelname)s - %(name)s - %(message)s",
"datefmt": "%d-%m-%Y:%H:%M:%S %z",
}
LOGGING_CONFIG["handlers"]["verbose"] = {
"formatter": "verbose",
"class": "logging.StreamHandler",
"stream": "ext://sys.stderr",
}
LOGGING_CONFIG["loggers"]["daiv_sandbox"] = {"level": settings.LOG_LEVEL, "handlers": ["verbose"]}
39 changes: 20 additions & 19 deletions daiv_sandbox/main.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,31 @@
import base64
import io
from logging.config import dictConfig
from pathlib import Path
from typing import Literal

import sentry_sdk
from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security.api_key import APIKeyHeader
from sentry_sdk.integrations.fastapi import FastApiIntegration

from daiv_sandbox import __version__
from daiv_sandbox.config import settings
from daiv_sandbox.languages import LanguageManager

from . import __version__
from .config import settings
from .schemas import ErrorMessage, RunCodeRequest, RunCodeResponse, RunRequest, RunResponse, RunResult
from .sessions import SandboxDockerSession
from daiv_sandbox.logs import LOGGING_CONFIG
from daiv_sandbox.schemas import ErrorMessage, RunCodeRequest, RunCodeResponse, RunRequest, RunResponse, RunResult
from daiv_sandbox.sessions import SandboxDockerSession

HEADER_API_KEY_NAME = "X-API-Key"


# Configure root logger
dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {"format": "[%(asctime)s] %(levelname)s - %(name)s - %(message)s", "datefmt": "%d-%m-%Y:%H:%M:%S %z"}
},
"handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose"}},
"loggers": {"daiv_sandbox": {"level": "DEBUG", "handlers": ["console"], "propagate": False}},
})
# Configure Sentry

if settings.SENTRY_DSN and settings.ENVIRONMENT != "local":
sentry_sdk.init(
dsn=str(settings.SENTRY_DSN),
environment=settings.ENVIRONMENT,
enable_tracing=settings.SENTRY_ENABLE_TRACING,
enable_tracing=bool(settings.SENTRY_ENABLE_TRACING),
profiles_sample_rate=1.0 if settings.SENTRY_ENABLE_TRACING else 0.0,
release=__version__,
integrations=[FastApiIntegration()],
)

description = """\
Expand Down Expand Up @@ -169,3 +157,16 @@ async def version() -> dict[Literal["version"], str]:
Get the version of the service.
"""
return {"version": __version__}


if __name__ == "__main__":
import uvicorn

uvicorn.run(
"daiv_sandbox.main:app",
host=settings.HOST,
port=settings.PORT,
log_config=LOGGING_CONFIG,
reload=settings.ENVIRONMENT == "local",
reload_dirs=["daiv_sandbox"],
)
Loading