Skip to content

Commit 35adfbb

Browse files
committed
Tweaks
Remove bind_logger now that we report file path and line Update Tracer for new logging
1 parent 2771809 commit 35adfbb

8 files changed

Lines changed: 36 additions & 40 deletions

File tree

docs/tutorials/static-drivers.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +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, import the singleton `logger` directly.
412+
arguments (the default logging level is INFO). To log messages from a driver, import the
413+
singleton `logger` directly.
413414

414415
Create a module-level logger to log status of the application start up. Create a class
415416
logger for `TemperatureControllerAttributeIO` to log the commands it sends.
@@ -431,7 +432,7 @@ Try setting a PV and check the console for the log message it prints.
431432

432433
A similar log message could be added for the update method of the IO, but this would be
433434
very verbose. For this use case FastCS provides the `Tracer` class, which is inherited
434-
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`
435436
level log messages that are disabled by default, but can be enabled at runtime.
436437

437438
Update the `send` method of the IO to log a message showing the query that was sent and
@@ -449,7 +450,8 @@ visible.
449450
::::
450451

451452
Enable tracing on the `power` attribute by calling `enable_tracing` and then enable a
452-
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`.
453455

454456
```
455457
In [1]: controller.power.enable_tracing()
@@ -469,7 +471,7 @@ In [1]: controller.power.enable_tracing()
469471
In [2]: controller.power.disable_tracing()
470472
```
471473

472-
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
473475
`topic`, so they also appear automatically, so the log messages show changes to the
474476
attribute throughout the stack: the query to the device and its response, the value the
475477
attribute is set to, and the value that the PV in the EPICS CA transport is set to.
@@ -481,7 +483,7 @@ The `Tracer` can also be used as a module-level instance for use in free functio
481483
```python
482484
from fastcs.tracer import Tracer
483485

484-
tracer = Tracer(__name__)
486+
tracer = Tracer()
485487

486488
def handle_attribute(attr):
487489
tracer.log_event("Handling attribute", topic=attr)

src/fastcs/control_system.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from fastcs.tracer import Tracer
1414
from fastcs.transports import ControllerAPI, Transport
1515

16-
tracer = Tracer(name=__name__)
16+
tracer = Tracer()
1717

1818

1919
class FastCS:

src/fastcs/logging/__init__.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -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

src/fastcs/logging/_logging.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ def format_record(record) -> str:
9090
time = f"{_time}{_timezone}"
9191

9292
name = record["extra"].pop("logger_name", None) or record["name"]
93+
message_pad = max(0, 100 - len(name))
9394

9495
sep = "<white>,</white> "
9596
if "extra" in record:
@@ -108,9 +109,8 @@ def format_record(record) -> str:
108109

109110
return f"""\
110111
<level>[{time} {record["level"].name[0]}]</level> \
111-
{record["message"]:<80} \
112-
[{record["file"].path}:{record["line"]}] \
113-
<green>[{name}]</green> \
112+
{record["message"]:<{message_pad}} \
113+
<green>{name} [{record["file"].path}:{record["line"]}]</green> \
114114
{extras}
115115
{{exception}}\
116116
"""

src/fastcs/tracer.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
from collections import defaultdict
22
from typing import Any
33

4-
from fastcs.logging import logger
4+
from fastcs.logging import logger as _logger
5+
6+
# Pass depth so that reported line number in log messages is `log_event` call site
7+
logger = _logger.opt(depth=1)
58

69

710
class Tracer:
@@ -16,9 +19,9 @@ class Tracer:
1619
object, or from another ``Tracer`` that uses the object as the ``topic``, will be
1720
logged.
1821
19-
Note: The global logger level must be set to ``TRACE`` for the messages to be logged
22+
Note: The logger level must be set to ``TRACE`` for the messages to be logged
2023
21-
Example usage:
24+
Example usage in interactive shell:
2225
.. code-block:: python
2326
2427
controller.ramp_rate.enable_tracing()
@@ -27,23 +30,20 @@ class Tracer:
2730
controller.connection.add_tracing_filter("query", "V?")
2831
controller.connection.remove_tracing_filter("query", "V?")
2932
controller.connection.disable_tracing()
30-
31-
:param name: The name of the logger. Attached to log messages as ``logger_name``.
32-
3333
"""
3434

35-
def __init__(self, name: str | None = None):
35+
def __init__(self):
3636
self.__tracing_enabled: bool = False
3737
self.__tracing_filters: dict[str, list[Any]] = defaultdict(list)
38-
self.__logger_name = name if name is not None else self.__class__.__name__
3938

4039
def log_event(self, event: str, topic: "Tracer | None" = None, *args, **kwargs):
4140
"""Log an event only if tracing is enabled and the filter matches
4241
43-
:param event: A message describing the event
44-
:param topic: Another `Tracer` related to this event to enable it to be logged
45-
:param args: Positional arguments for underlying logger
46-
:param kwargs: Keyword arguments for underlying logger
42+
Args:
43+
event: A message describing the event
44+
topic: Another `Tracer` related to this event to enable it to be logged
45+
args: Positional arguments for underlying logger
46+
kwargs: Keyword arguments for underlying logger
4747
4848
"""
4949
if self.__tracing_enabled or (topic is not None and topic.__tracing_enabled): # noqa: SLF001
@@ -54,7 +54,7 @@ def log_event(self, event: str, topic: "Tracer | None" = None, *args, **kwargs):
5454
else:
5555
return
5656

57-
logger.trace(event, *args, logger_name=self.__logger_name, **kwargs)
57+
logger.trace(event, *args, **kwargs)
5858

5959
def enable_tracing(self):
6060
"""Enable trace logging for this object"""

src/fastcs/transports/controller_api.py

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

66
from fastcs.attributes import Attribute, AttributeIORef, AttrR
77
from fastcs.methods import Command, Scan, ScanCallback
8-
from fastcs.tracer import Tracer
98
from fastcs.util import ONCE
109

11-
tracer = Tracer(name=__name__)
12-
1310

1411
@dataclass
1512
class ControllerAPI:

src/fastcs/transports/epics/ca/ioc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
EPICS_MAX_NAME_LENGTH = 60
2828

2929

30-
tracer = Tracer(name=__name__)
30+
tracer = Tracer()
3131

3232

3333
class EpicsCAIOC:

src/fastcs/transports/epics/pva/_pv_handlers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
p4p_timestamp_now,
2222
)
2323

24-
tracer = Tracer(name=__name__)
24+
tracer = Tracer()
2525

2626

2727
class WritePvHandler:

0 commit comments

Comments
 (0)