Enabling Logtail Only in Production

In many development and testing environments, it’s often desirable to disable or reduce logging to avoid performance overhead. However, for production environments, it’s crucial to have robust logging in place for monitoring and troubleshooting. This guide will demonstrate how to configure Logtail to be enabled only in production environments.

Using Environment Variables

Define a Configuration Model:

Python

from pydantic import BaseModel

class Settings(BaseModel):
debug: bool = True
logtail_enabled: bool = False

Load the Configuration:

Python

from dotenv import load_dotenv
from pathlib import Path

def get_settings():
load_dotenv()
return Settings()

Check for Production Mode:

Python

def initialize_logging(settings: Settings):
if settings.logtail_enabled:
# Initialize Logtail
client = logtail.Client(api_key=”YOUR_API_KEY”)
logger = client.logger(“your_application_name”)
else:
# Create a local logger for development
logger = logging.getLogger(name)
# Configure logger for development

Use the Logger:

Python

from app.logging import initialize_logging

app = FastAPI()

@app.on_event(“startup”)
async def startup():
settings = get_settings()
initialize_logging(settings)

Setting the Environment Variable

Set the LOGTAIL_ENABLED environment variable to True in your production environment:

Bash

export LOGTAIL_ENABLED=True

Conditional Logging

You can use the settings.logtail_enabled flag to conditionally enable or disable Logtail within your application:

Python

@app.get("/")
def read_root(settings: Settings = Depends(get_settings)):
    if settings.logtail_enabled:
        logger.info("Received a GET request to /")
    else:
        print("Received a GET request to /")

By using this approach, you can effectively configure Logtail to be enabled only in production environments, ensuring that your application’s performance is not impacted by logging overhead during development and testing.

Database Integration Overview
Integrating Logtail for Cloud-Based Logging in FastAPI

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?