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

Use logfire.configure() consistently in docs #204

Merged
merged 6 commits into from
May 23, 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
2 changes: 2 additions & 0 deletions docs/guides/advanced/sampling.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ You can tweak sampling on a per module or per code block basis using
```python
import logfire

logfire.configure()

sampled = logfire.with_trace_sample_rate(0.5)

with sampled.span("outer"): # This span will be sampled 50% of the time
Expand Down
11 changes: 8 additions & 3 deletions docs/guides/first_steps/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,18 @@ Upon successful authentication, credentials are stored in `~/.logfire/default.to
The first time you use Logfire in a new environment, you'll need to set up a project. A Logfire project is like a
namespace for organizing your data. All data sent to Logfire must be associated with a project.

To use Logfire, simply import it and call the desired logging function:
To use Logfire, simply import it, configure, and call the desired logging function:

```py
import logfire

logfire.info('Hello, {name}!', name='world') # (1)!
logfire.configure() # (1)!

logfire.info('Hello, {name}!', name='world') # (2)!
```

1. This will log `Hello world!` with `info` level.
1. This should be called once before logging to initialize **Logfire**.
2. This will log `Hello world!` with `info` level.

!!! note

Expand Down Expand Up @@ -105,6 +108,8 @@ import logfire
cwd = Path.cwd()
total_size = 0

logfire.configure()

with logfire.span('counting size of {cwd=}', cwd=cwd):
for path in cwd.iterdir():
if path.is_file():
Expand Down
1 change: 1 addition & 0 deletions docs/guides/onboarding_checklist/add_auto_tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ you could create another file outside of the `app` package, e.g:
```py title="main.py"
import logfire

logfire.configure()
logfire.install_auto_tracing(modules=['app'])

from app.main import main
Expand Down
10 changes: 6 additions & 4 deletions docs/guides/onboarding_checklist/integrate.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,21 @@ The minimal configuration would be the following:
```py hl_lines="5"
from logging import basicConfig

from logfire.integrations.logging import LogfireLoggingHandler
import logfire

basicConfig(handlers=[LogfireLoggingHandler()])
logfire.configure()
basicConfig(handlers=[logfire.LogfireLoggingHandler()])
```

Now imagine, that you have a logger in your application:

```py hl_lines="7-8" title="main.py"
from logging import basicConfig, getLogger

from logfire.integrations.logging import LogfireLoggingHandler
import logfire

basicConfig(handlers=[LogfireLoggingHandler()])
logfire.configure()
basicConfig(handlers=[logfire.LogfireLoggingHandler()])

logger = getLogger(__name__)
logger.error("Hello %s!", "Fred")
Expand Down
21 changes: 13 additions & 8 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,21 @@ Then in your code:
import logfire
from datetime import date

logfire.info('Hello, {name}!', name='world') # (1)!
logfire.configure() # (1)!

with logfire.span('Asking the user their {question}', question='age'): # (2)!
logfire.info('Hello, {name}!', name='world') # (2)!

with logfire.span('Asking the user their {question}', question='age'): # (3)!
user_input = input('How old are you [YYYY-mm-dd]? ')
dob = date.fromisoformat(user_input) # (3)!
logfire.debug('{dob=} {age=!r}', dob=dob, age=date.today() - dob) # (4)!
dob = date.fromisoformat(user_input) # (4)!
logfire.debug('{dob=} {age=!r}', dob=dob, age=date.today() - dob) # (5)!
```

1. This will log `Hello world!` with `info` level. The first time a `logfire` command is run, if no project is configured for the current directory, an interactive prompt will walk you through creating a project.
2. Spans allow you to nest other Logfire calls, and also to measure how long code takes to run. They are the fundamental building block of traces!
3. Attempt to extract a date from the user input. If any exception is raised, the outer span will include the details of the exception.
4. This will log for example `dob=2000-01-01 age=datetime.timedelta(days=8838)` with `debug` level.
1. This should be called once before logging to initialize Logfire. If no project is configured for the current directory, an interactive prompt will walk you through creating a project.
2. This will log `Hello world!` with `info` level. `name='world'` will be stored as an attributed that can be queried with SQL.
3. Spans allow you to nest other Logfire calls, and also to measure how long code takes to run. They are the fundamental building block of traces!
4. Attempt to extract a date from the user input. If any exception is raised, the outer span will include the details of the exception.
5. This will log for example `dob=2000-01-01 age=datetime.timedelta(days=8838)` with `debug` level.

This might look similar to simple logging, but it's much more powerful — you get:

Expand All @@ -114,6 +117,8 @@ from datetime import date
import logfire
from pydantic import BaseModel

logfire.configure()

class User(BaseModel):
name: str
country_code: str
Expand Down
2 changes: 2 additions & 0 deletions docs/integrations/anthropic.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import logfire

client = anthropic.Anthropic()

logfire.configure()
logfire.instrument_anthropic(client) # (1)!

response = client.messages.create(
Expand Down Expand Up @@ -66,6 +67,7 @@ from rich.live import Live
from rich.markdown import Markdown

client = anthropic.AsyncAnthropic()
logfire.configure()
logfire.instrument_anthropic(client)


Expand Down
1 change: 1 addition & 0 deletions docs/integrations/fastapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def request_attributes_mapper(request, attributes):
return None


logfire.configure()
logfire.instrument_fastapi(app, request_attributes_mapper=request_attributes_mapper)
```

Expand Down
5 changes: 3 additions & 2 deletions docs/integrations/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ every standard library log record.
```py title="main.py"
from logging import basicConfig, getLogger

from logfire.integrations.logging import LogfireLoggingHandler
import logfire

basicConfig(handlers=[LogfireLoggingHandler()])
logfire.configure()
basicConfig(handlers=[logfire.LogfireLoggingHandler()])

logger = getLogger(__name__)

Expand Down
3 changes: 3 additions & 0 deletions docs/integrations/openai.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import logfire

client = openai.Client()

logfire.configure()
logfire.instrument_openai(client) # (1)!

response = client.chat.completions.create(
Expand Down Expand Up @@ -61,6 +62,7 @@ import logfire

async def main():
client = openai.AsyncClient()
logfire.configure()
logfire.instrument_openai(client)

response = await client.images.generate(
Expand Down Expand Up @@ -98,6 +100,7 @@ from rich.live import Live
from rich.markdown import Markdown

client = openai.AsyncClient()
logfire.configure()
logfire.instrument_openai(client)

async def main():
Expand Down
2 changes: 2 additions & 0 deletions docs/integrations/psycopg.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ To add SQL comments to the end of your queries to enrich your database logs with
```python
import logfire

logfire.configure()
logfire.instrument_psycopg(enable_commenter=True)
```

Expand All @@ -106,6 +107,7 @@ e.g:
```python
import logfire

logfire.configure()
logfire.instrument_psycopg(enable_commenter=True, commenter_options={'db_driver': False, 'dbapi_threadsafety': False})
```

Expand Down
5 changes: 3 additions & 2 deletions docs/integrations/structlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
from dataclasses import dataclass

import structlog
import logfire

from logfire.integrations.structlog import LogfireProcessor
logfire.configure()

structlog.configure(
processors=[
Expand All @@ -16,7 +17,7 @@ structlog.configure(
structlog.processors.StackInfoRenderer(),
structlog.dev.set_exc_info,
structlog.processors.TimeStamper(fmt='%Y-%m-%d %H:%M:%S', utc=False),
LogfireProcessor(),
logfire.StructlogProcessor(),
structlog.dev.ConsoleRenderer(),
],
)
Expand Down
4 changes: 4 additions & 0 deletions logfire/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
from ._internal.exporters.file import load_file as load_spans_from_file
from ._internal.main import Logfire, LogfireSpan
from ._internal.scrubbing import ScrubMatch
from .integrations.logging import LogfireLoggingHandler
from .integrations.structlog import LogfireProcessor as StructlogProcessor
from .version import VERSION

DEFAULT_LOGFIRE_INSTANCE = Logfire()
Expand Down Expand Up @@ -99,4 +101,6 @@ def loguru_handler() -> dict[str, Any]:
'METRICS_PREFERRED_TEMPORALITY',
'ScrubMatch',
'VERSION',
'StructlogProcessor',
'LogfireLoggingHandler',
)
34 changes: 34 additions & 0 deletions logfire/_internal/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ def trace(
```py
import logfire

logfire.configure()

logfire.trace('This is a trace log')
```

Expand Down Expand Up @@ -262,6 +264,8 @@ def debug(
```py
import logfire

logfire.configure()

logfire.debug('This is a debug log')
```

Expand Down Expand Up @@ -292,6 +296,8 @@ def info(
```py
import logfire

logfire.configure()

logfire.info('This is an info log')
```

Expand Down Expand Up @@ -322,6 +328,8 @@ def notice(
```py
import logfire

logfire.configure()

logfire.notice('This is a notice log')
```

Expand Down Expand Up @@ -352,6 +360,8 @@ def warn(
```py
import logfire

logfire.configure()

logfire.warn('This is a warning log')
```

Expand Down Expand Up @@ -382,6 +392,8 @@ def error(
```py
import logfire

logfire.configure()

logfire.error('This is an error log')
```

Expand Down Expand Up @@ -412,6 +424,8 @@ def fatal(
```py
import logfire

logfire.configure()

logfire.fatal('This is a fatal log')
```

Expand Down Expand Up @@ -467,6 +481,8 @@ def span(
```py
import logfire

logfire.configure()

with logfire.span('This is a span {a=}', a='data'):
logfire.info('new log 1')
```
Expand Down Expand Up @@ -501,6 +517,8 @@ def instrument(
```py
import logfire

logfire.configure()


@logfire.instrument('This is a span {a=}')
def my_function(a: int):
Expand Down Expand Up @@ -534,6 +552,8 @@ def log(
```py
import logfire

logfire.configure()

logfire.log('info', 'This is a log {a}', {'a': 'Apple'})
```

Expand Down Expand Up @@ -640,6 +660,8 @@ def with_tags(self, *tags: str) -> Logfire:
```py
import logfire

logfire.configure()

local_logfire = logfire.with_tags('tag1')
local_logfire.info('a log message', _tags=['tag2'])

Expand Down Expand Up @@ -862,6 +884,7 @@ def instrument_openai(
import openai

client = openai.OpenAI()
logfire.configure()
logfire.instrument_openai(client)

response = client.chat.completions.create(
Expand Down Expand Up @@ -933,6 +956,7 @@ def instrument_anthropic(
import anthropic

client = anthropic.Anthropic()
logfire.configure()
logfire.instrument_anthropic(client)

response = client.messages.create(
Expand Down Expand Up @@ -1085,6 +1109,7 @@ def metric_counter(self, name: str, *, unit: str = '', description: str = '') ->
```py
import logfire

logfire.configure()
counter = logfire.metric_counter('exceptions', unit='1', description='Number of exceptions caught')

try:
Expand Down Expand Up @@ -1114,6 +1139,7 @@ def metric_histogram(self, name: str, *, unit: str = '', description: str = '')
```py
import logfire

logfire.configure()
histogram = logfire.metric_histogram('bank.amount_transferred', unit='$', description='Amount transferred')


Expand Down Expand Up @@ -1141,6 +1167,7 @@ def metric_gauge(self, name: str, *, unit: str = '', description: str = '') -> G
```py
import logfire

logfire.configure()
gauge = logfire.metric_gauge('system.cpu_usage', unit='%', description='CPU usage')


Expand Down Expand Up @@ -1169,6 +1196,7 @@ def metric_up_down_counter(self, name: str, *, unit: str = '', description: str
```py
import logfire

logfire.configure()
up_down_counter = logfire.metric_up_down_counter('users.logged_in', unit='1', description='Users logged in')


Expand Down Expand Up @@ -1210,6 +1238,8 @@ def metric_counter_callback(
import psutil
from opentelemetry.metrics import CallbackOptions, Observation

logfire.configure()


def cpu_usage_callback(options: CallbackOptions):
cpu_percents = psutil.cpu_percent(percpu=True)
Expand Down Expand Up @@ -1251,6 +1281,8 @@ def metric_gauge_callback(
import logfire
from opentelemetry.metrics import CallbackOptions, Observation

logfire.configure()


def thread_count_callback(options: CallbackOptions):
yield Observation(threading.active_count())
Expand Down Expand Up @@ -1288,6 +1320,8 @@ def metric_up_down_counter_callback(
import logfire
from opentelemetry.metrics import CallbackOptions, Observation

logfire.configure()

items = []


Expand Down
Loading