Skip to content

Commit 1008960

Browse files
313 make logger use file path and line (#323)
* Use file path and line number in format record string * Remove redundant bind_logger function * Remove all calls to bind_logger. Replace import with logger where still used * Update logging docs to remove mention of bind_logger * Update emphasize-lines line numbers after edits * Don't disable logging by default --------- Co-authored-by: Gary Yendell <gary.yendell@diamond.ac.uk>
1 parent dbb85c4 commit 1008960

20 files changed

Lines changed: 53 additions & 109 deletions

File tree

docs/snippets/static14.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@
1010
from fastcs.controllers import Controller
1111
from fastcs.datatypes import Enum, Float, Int, String
1212
from fastcs.launch import FastCS
13-
from fastcs.logging import bind_logger, configure_logging
13+
from fastcs.logging import configure_logging, logger
1414
from fastcs.methods import command, scan
1515
from fastcs.transports.epics import EpicsGUIOptions, EpicsIOCOptions
1616
from fastcs.transports.epics.ca import EpicsCATransport
1717

18-
logger = bind_logger(__name__)
19-
2018
NumberT = TypeVar("NumberT", int, float)
2119

2220

@@ -33,8 +31,6 @@ class TemperatureControllerAttributeIO(
3331
def __init__(self, connection: IPConnection, suffix: str = ""):
3432
super().__init__()
3533

36-
self.logger = bind_logger(__class__.__name__)
37-
3834
self._connection = connection
3935
self._suffix = suffix
4036

@@ -49,7 +45,7 @@ async def send(
4945
) -> None:
5046
command = f"{attr.io_ref.name}{self._suffix}={attr.dtype(value)}"
5147

52-
self.logger.info("Sending attribute value", command=command, attribute=attr)
48+
logger.info("Sending attribute value", command=command, attribute=attr)
5349

5450
await self._connection.send_command(f"{command}\r\n")
5551

docs/snippets/static15.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@
1010
from fastcs.controllers import Controller
1111
from fastcs.datatypes import Enum, Float, Int, String
1212
from fastcs.launch import FastCS
13-
from fastcs.logging import LogLevel, bind_logger, configure_logging
13+
from fastcs.logging import LogLevel, configure_logging, logger
1414
from fastcs.methods import command, scan
1515
from fastcs.transports.epics import EpicsGUIOptions, EpicsIOCOptions
1616
from fastcs.transports.epics.ca import EpicsCATransport
1717

18-
logger = bind_logger(__name__)
19-
2018
NumberT = TypeVar("NumberT", int, float)
2119

2220

@@ -33,8 +31,6 @@ class TemperatureControllerAttributeIO(
3331
def __init__(self, connection: IPConnection, suffix: str = ""):
3432
super().__init__()
3533

36-
self.logger = bind_logger(__class__.__name__)
37-
3834
self._connection = connection
3935
self._suffix = suffix
4036

@@ -52,7 +48,7 @@ async def send(
5248
) -> None:
5349
command = f"{attr.io_ref.name}{self._suffix}={attr.dtype(value)}"
5450

55-
self.logger.info("Sending attribute value", command=command, attribute=attr)
51+
logger.info("Sending attribute value", command=command, attribute=attr)
5652

5753
await self._connection.send_command(f"{command}\r\n")
5854

docs/tutorials/static-drivers.md

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -409,10 +409,8 @@ DEMO:R1:Enabled_RBV Off
409409

410410
FastCS has convenient logging support to provide status and metrics from the
411411
application. To enable logging from the core framework call `configure_logging` with no
412-
arguments (the default logging level is INFO). To log messages from a driver, either
413-
import the singleton `logger` directly, or to provide more context to the message, call
414-
`bind_logger` with a name (usually either the name of the module or the name of the
415-
class).
412+
arguments (the default logging level is INFO). To log messages from a driver, import the
413+
singleton `logger` directly.
416414

417415
Create a module-level logger to log status of the application start up. Create a class
418416
logger for `TemperatureControllerAttributeIO` to log the commands it sends.
@@ -421,7 +419,7 @@ logger for `TemperatureControllerAttributeIO` to log the commands it sends.
421419
:class: dropdown, hint
422420

423421
:::{literalinclude} /snippets/static14.py
424-
:emphasize-lines: 15,20-21,53-55,116,123
422+
:emphasize-lines: 13,48,110,117
425423
:::
426424

427425
::::
@@ -434,7 +432,7 @@ Try setting a PV and check the console for the log message it prints.
434432

435433
A similar log message could be added for the update method of the IO, but this would be
436434
very verbose. For this use case FastCS provides the `Tracer` class, which is inherited
437-
by `AttributeIO`, among other core FastCS classes. This adds a enables logging `TRACE`
435+
by `AttributeIO`, among other core FastCS classes. This enables the logging of `TRACE`
438436
level log messages that are disabled by default, but can be enabled at runtime.
439437

440438
Update the `send` method of the IO to log a message showing the query that was sent and
@@ -446,13 +444,14 @@ visible.
446444
:class: dropdown, hint
447445

448446
:::{literalinclude} /snippets/static15.py
449-
:emphasize-lines: 15,47-49,119
447+
:emphasize-lines: 13,49-51,120
450448
:::
451449

452450
::::
453451

454452
Enable tracing on the `power` attribute by calling `enable_tracing` and then enable a
455-
ramp so that the value updates. Check the console to see the messages. Call `disable_tracing` to disable the log messages for `power.
453+
ramp so that the value updates. Check the console to see the messages. Call
454+
`disable_tracing` to disable the log messages for `power`.
456455

457456
```
458457
In [1]: controller.power.enable_tracing()
@@ -472,7 +471,7 @@ In [1]: controller.power.enable_tracing()
472471
In [2]: controller.power.disable_tracing()
473472
```
474473

475-
These log messages includes other trace loggers that log messages with `power` as the
474+
These log messages include other trace loggers that log messages with `power` as the
476475
`topic`, so they also appear automatically, so the log messages show changes to the
477476
attribute throughout the stack: the query to the device and its response, the value the
478477
attribute is set to, and the value that the PV in the EPICS CA transport is set to.
@@ -484,7 +483,7 @@ The `Tracer` can also be used as a module-level instance for use in free functio
484483
```python
485484
from fastcs.tracer import Tracer
486485

487-
tracer = Tracer(__name__)
486+
tracer = Tracer()
488487

489488
def handle_attribute(attr):
490489
tracer.log_event("Handling attribute", topic=attr)

src/fastcs/attributes/attr_r.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@
88
from fastcs.attributes.attribute_io_ref import AttributeIORefT
99
from fastcs.attributes.util import AttrValuePredicate, PredicateEvent
1010
from fastcs.datatypes import DataType, DType_T
11-
from fastcs.logging import bind_logger
12-
13-
logger = bind_logger(logger_name=__name__)
14-
11+
from fastcs.logging import logger
1512

1613
AttrIOUpdateCallback = Callable[["AttrR[DType_T, Any]"], Awaitable[None]]
1714
"""An AttributeIO callback that takes an AttrR and updates its value"""

src/fastcs/attributes/attr_rw.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
from fastcs.attributes.attribute import AttributeAccessMode
44
from fastcs.attributes.attribute_io_ref import AttributeIORefT
55
from fastcs.datatypes import DataType, DType_T
6-
from fastcs.logging import bind_logger
7-
8-
logger = bind_logger(logger_name=__name__)
96

107

118
class AttrRW(AttrR[DType_T, AttributeIORefT], AttrW[DType_T, AttributeIORefT]):

src/fastcs/attributes/attr_w.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@
55
from fastcs.attributes.attribute import Attribute, AttributeAccessMode
66
from fastcs.attributes.attribute_io_ref import AttributeIORefT
77
from fastcs.datatypes import DataType, DType_T
8-
from fastcs.logging import bind_logger
9-
10-
logger = bind_logger(logger_name=__name__)
11-
8+
from fastcs.logging import logger
129

1310
AttrOnPutCallback = Callable[["AttrW[DType_T, Any]", DType_T], Awaitable[None]]
1411
"""Callbacks to be called when the setpoint of an attribute is changed"""

src/fastcs/attributes/attribute.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,8 @@
44

55
from fastcs.attributes.attribute_io_ref import AttributeIORefT
66
from fastcs.datatypes import DataType, DType, DType_T
7-
from fastcs.logging import bind_logger
87
from fastcs.tracer import Tracer
98

10-
logger = bind_logger(logger_name=__name__)
11-
129
AttributeAccessMode = Literal["r", "w", "rw"]
1310

1411

src/fastcs/control_system.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@
88
from IPython.terminal.embed import InteractiveShellEmbed
99

1010
from fastcs.controllers import BaseController, Controller
11-
from fastcs.logging import bind_logger
11+
from fastcs.logging import logger
1212
from fastcs.methods import ScanCallback
1313
from fastcs.tracer import Tracer
1414
from fastcs.transports import ControllerAPI, Transport
1515

16-
tracer = Tracer(name=__name__)
17-
logger = bind_logger(logger_name=__name__)
16+
tracer = Tracer()
1817

1918

2019
class FastCS:

src/fastcs/controllers/base_controller.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@
66
from typing import _GenericAlias, get_args, get_origin, get_type_hints # type: ignore
77

88
from fastcs.attributes import AnyAttributeIO, Attribute, AttrR, AttrW, HintedAttribute
9-
from fastcs.logging import bind_logger
9+
from fastcs.logging import logger
1010
from fastcs.methods import Command, Scan, UnboundCommand, UnboundScan
1111
from fastcs.tracer import Tracer
1212

13-
logger = bind_logger(logger_name=__name__)
14-
1513

1614
class BaseController(Tracer):
1715
"""Base class for controllers

src/fastcs/logging/__init__.py

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from ._graylog import GraylogStaticFields as GraylogStaticFields
88
from ._graylog import parse_graylog_env_fields as parse_graylog_env_fields
99
from ._graylog import parse_graylog_static_fields as parse_graylog_static_fields
10-
from ._logging import Logger, LogLevel, _configure_logger
10+
from ._logging import LogLevel, _configure_logger
1111

1212
logger = _logger.bind(logger_name="fastcs")
1313
"""FastCS logger
@@ -21,33 +21,30 @@
2121
and metrics in graylog.
2222
2323
It is best to keep the message short and use extra fields for additional information for
24-
messages to be formatted nicely in the console. To add kwargs to format the message
25-
without them appearing as extra fields, prepend the key with ``_``.
24+
messages to be formatted nicely in the console.
2625
2726
.. code-block:: python
2827
2928
from fastcs.logging import logger
3029
3130
logger.info("PV put: {pv} = {value}", pv=pv, value=value)
3231
33-
By default messages will be logged with the name ``fastcs``. Within different modules
34-
and classes it can be useful to override this name. This can be done with the ``bind``
35-
method. To create a module logger with its name
32+
To add kwargs to format the message without them appearing as extra fields, prepend the
33+
key with ``_``.
34+
35+
By default messages will be logged with the name ``fastcs``. Within a driver it may be
36+
useful to set a distinct logger name. This can be done with the ``bind`` method. To
37+
create a new logger with the the name of the driver, use the following in a logging.py
38+
module and use it throughout the package instead of the fastcs logger:
3639
3740
.. code-block:: python
3841
3942
from fastcs.logging import logger as _logger
4043
41-
logger = _logger.bind(logger_name=__name__)
42-
43-
or to create a class logger with its name
44-
45-
.. code-block:: python
46-
47-
self.logger = _logger.bind(logger_name=__class__.__name__)
44+
logger = _logger.bind(logger_name="fastcs-driver")
4845
4946
As standard ``loguru`` supports ``trace`` level monitoring, but it should not be used in
50-
fastcs. Instead there is a ``Tracer`` class for verbose logging with fine-grained
47+
fastcs. Instead there is a `Tracer` class for verbose logging with fine-grained
5148
controls that can be enabled by the user at runtime.
5249
5350
Use ``configure_logging`` to re-configure the logger at runtime. For more advanced
@@ -57,18 +54,6 @@
5754
"""
5855

5956

60-
def bind_logger(logger_name: str) -> Logger:
61-
"""Create a wrapper of the singleton fastcs logger with the given name bound
62-
63-
The name will be displayed in all log messages from the returned wrapper.
64-
65-
See the docstring for ``fastcs.logging.logger`` for more information.
66-
67-
"""
68-
69-
return logger.bind(logger_name=logger_name)
70-
71-
7257
def configure_logging(
7358
level: LogLevel = LogLevel.INFO,
7459
graylog_endpoint: GraylogEndpoint | None = None,
@@ -94,10 +79,6 @@ def configure_logging(
9479
)
9580

9681

97-
# Configure logger with defaults - INFO level and disabled
98-
_configure_logger(logger)
99-
100-
10182
class _StdLoggingInterceptHandler(logging.Handler):
10283
"""A std logging handler to forward messages to loguru with nice formatting."""
10384

0 commit comments

Comments
 (0)