Skip to main content

hyperactor/
subject.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! Log subject for structured logging.
10//!
11//! Each log message in hyperactor can have a **subject**: the entity the
12//! message pertains to (an actor, a proc, a channel, etc.). The subject
13//! is set as a tracing span field and rendered prominently in log output.
14//!
15//! ```text
16//! <actor metatls:host:1234,local,my_actor[0]> undeliverable message, ...
17//! ```
18
19use std::fmt;
20
21use crate::ActorAddr;
22use crate::ProcAddr;
23
24/// Identifies the entity a log message pertains to.
25///
26/// Used as a tracing span field via `%actor_id.subject()`.
27/// The GlogSink recognizes the well-known `subject` field and renders
28/// it as a prefix; other subscribers see it as a regular string field.
29pub struct Subject<'a> {
30    kind: &'static str,
31    id: &'a dyn fmt::Display,
32}
33
34impl<'a> Subject<'a> {
35    /// An actor subject.
36    pub fn actor(id: &'a (impl fmt::Display + 'a)) -> Self {
37        Self { kind: "actor", id }
38    }
39
40    /// A proc subject.
41    pub fn proc(id: &'a (impl fmt::Display + 'a)) -> Self {
42        Self { kind: "proc", id }
43    }
44}
45
46impl fmt::Display for Subject<'_> {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "<{} {}>", self.kind, self.id)
49    }
50}
51
52/// Extension trait for types that can be used as a log subject.
53pub trait AsSubject: fmt::Display {
54    /// Return a [`Subject`] for this ID.
55    fn subject(&self) -> Subject<'_>;
56}
57
58impl AsSubject for ActorAddr {
59    fn subject(&self) -> Subject<'_> {
60        Subject::actor(self)
61    }
62}
63
64impl AsSubject for ProcAddr {
65    fn subject(&self) -> Subject<'_> {
66        Subject::proc(self)
67    }
68}