cargo/util/
log_message.rs

1//! Messages for logging.
2
3use std::borrow::Cow;
4use std::io::Write;
5use std::path::PathBuf;
6
7use cargo_util_schemas::core::PackageIdSpec;
8use jiff::Timestamp;
9use serde::Deserialize;
10use serde::Serialize;
11
12use crate::core::compiler::CompileMode;
13use crate::core::compiler::fingerprint::DirtyReason;
14
15/// A log message.
16///
17/// Each variant represents a different type of event.
18#[derive(Serialize, Deserialize)]
19#[serde(tag = "reason", rename_all = "kebab-case")]
20pub enum LogMessage {
21    /// Emitted when a build starts.
22    BuildStarted {
23        /// Current working directory.
24        cwd: PathBuf,
25        /// Host triple.
26        host: String,
27        /// Number of parallel jobs.
28        jobs: u32,
29        /// Available parallelism of the compilation environment.
30        num_cpus: Option<u64>,
31        /// Build profile name (e.g., "dev", "release").
32        profile: String,
33        /// The rustc version (`1.23.4-beta.2`).
34        rustc_version: String,
35        /// The rustc verbose version information (the output of `rustc -vV`).
36        rustc_version_verbose: String,
37        /// Target directory for build artifacts.
38        target_dir: PathBuf,
39        /// Workspace root directory.
40        workspace_root: PathBuf,
41    },
42    /// Emitted when resolving dependencies starts.
43    ResolutionStarted {
44        /// Seconds elapsed from build start.
45        elapsed: f64,
46    },
47    /// Emitted when resolving dependencies finishes.
48    ResolutionFinished {
49        /// Seconds elapsed from build start.
50        elapsed: f64,
51    },
52    /// Emitted when unit graph generation starts.
53    UnitGraphStarted {
54        /// Seconds elapsed from build start.
55        elapsed: f64,
56    },
57    /// Emitted when unit graph generation finishes.
58    UnitGraphFinished {
59        /// Seconds elapsed from build start.
60        elapsed: f64,
61    },
62    /// Emitted when a compilation unit is registered in the unit graph,
63    /// right before [`LogMessage::UnitGraphFinished`] that Cargo finalizes
64    /// the unit graph.
65    UnitRegistered {
66        /// Package ID specification.
67        package_id: PackageIdSpec,
68        /// Cargo target (lib, bin, example, etc.).
69        target: Target,
70        /// The compilation action this unit is for (check, build, test, etc.).
71        mode: CompileMode,
72        /// The target platform this unit builds for.
73        ///
74        /// It is either a [target triple] the compiler accepts,
75        /// or a file name with the `json` extension for a [custom target].
76        ///
77        /// [target triple]: https://doc.rust-lang.org/nightly/rustc/platform-support.html
78        /// [custom target]: https://doc.rust-lang.org/nightly/rustc/targets/custom.html
79        platform: String,
80        /// Unit index for compact reference in subsequent events.
81        index: u64,
82        /// Enabled features.
83        #[serde(default, skip_serializing_if = "Vec::is_empty")]
84        features: Vec<String>,
85        /// Whether this is requested to build by user directly,
86        /// like via the `-p` flag or the default workspace members.
87        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
88        requested: bool,
89        /// Unit indices that this unit depends on.
90        #[serde(default, skip_serializing_if = "Vec::is_empty")]
91        dependencies: Vec<u64>,
92    },
93    /// Emitted when a compilation unit starts.
94    UnitStarted {
95        /// Unit index from the associated unit-registered event.
96        index: u64,
97        /// Seconds elapsed from build start.
98        elapsed: f64,
99    },
100    /// Emitted when a section (e.g., rmeta, link) of the compilation unit finishes.
101    UnitRmetaFinished {
102        /// Unit index from the associated unit-registered event.
103        index: u64,
104        /// Seconds elapsed from build start.
105        elapsed: f64,
106        /// Unit indices that were unblocked by this rmeta completion.
107        #[serde(default, skip_serializing_if = "Vec::is_empty")]
108        unblocked: Vec<u64>,
109    },
110    /// Emitted when a section (e.g., rmeta, link) of the compilation unit starts.
111    ///
112    /// Requires `-Zsection-timings` to be enabled.
113    UnitSectionStarted {
114        /// Unit index from the associated unit-registered event.
115        index: u64,
116        /// Seconds elapsed from build start.
117        elapsed: f64,
118        /// Section name from rustc's `-Zjson=timings` (e.g., "codegen", "link").
119        section: String,
120    },
121    /// Emitted when a section (e.g., rmeta, link) of the compilation unit finishes.
122    ///
123    /// Requires `-Zsection-timings` to be enabled.
124    UnitSectionFinished {
125        /// Unit index from the associated unit-registered event.
126        index: u64,
127        /// Seconds elapsed from build start.
128        elapsed: f64,
129        /// Section name from rustc's `-Zjson=timings` (e.g., "codegen", "link").
130        section: String,
131    },
132    /// Emitted when a compilation unit finishes.
133    UnitFinished {
134        /// Unit index from the associated unit-registered event.
135        index: u64,
136        /// Seconds elapsed from build start.
137        elapsed: f64,
138        /// Unit indices that were unblocked by this completion.
139        #[serde(default, skip_serializing_if = "Vec::is_empty")]
140        unblocked: Vec<u64>,
141    },
142    /// Emitted when rebuild fingerprint information is determined for a unit.
143    UnitFingerprint {
144        /// Unit index from the associated unit-registered event.
145        index: u64,
146        /// Status of the rebuild detection fingerprint of this unit
147        status: FingerprintStatus,
148        /// Reason why the unit is dirty and needs rebuilding.
149        #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
150        cause: Option<DirtyReason>,
151    },
152}
153
154/// Cargo target information.
155#[derive(Serialize, Deserialize)]
156pub struct Target {
157    /// Target name.
158    pub name: String,
159    /// Target kind (lib, bin, test, bench, example, build-script).
160    pub kind: Cow<'static, str>,
161}
162
163/// Status of the rebuild detection fingerprint.
164#[derive(Serialize, Deserialize)]
165#[serde(rename_all = "kebab-case")]
166pub enum FingerprintStatus {
167    /// There is no previous fingerprints for this unit.
168    /// Might be a brand-new build.
169    New,
170    /// The current fingerprint doesn't match the previous fingerprints.
171    /// Rebuild needed.
172    Dirty,
173    /// The current fingerprint matches the previous fingerprints.
174    /// No rebuild needed.
175    Fresh,
176}
177
178impl From<&crate::core::Target> for Target {
179    fn from(target: &crate::core::Target) -> Self {
180        use crate::core::TargetKind;
181        Self {
182            name: target.name().to_string(),
183            kind: match target.kind() {
184                TargetKind::Lib(..) => "lib",
185                TargetKind::Bin => "bin",
186                TargetKind::Test => "test",
187                TargetKind::Bench => "bench",
188                TargetKind::ExampleLib(..) | TargetKind::ExampleBin => "example",
189                TargetKind::CustomBuild => "build-script",
190            }
191            .into(),
192        }
193    }
194}
195
196impl LogMessage {
197    /// Serializes this message as a JSON log line directly to the writer.
198    pub fn write_json_log<W: Write>(&self, writer: &mut W, run_id: &str) -> std::io::Result<()> {
199        #[derive(Serialize)]
200        struct LogEntry<'a> {
201            run_id: &'a str,
202            timestamp: Timestamp,
203            #[serde(flatten)]
204            msg: &'a LogMessage,
205        }
206
207        let entry = LogEntry {
208            run_id,
209            timestamp: Timestamp::now(),
210            msg: self,
211        };
212
213        serde_json::to_writer(&mut *writer, &entry)?;
214        writer.write_all(b"\n")?;
215        Ok(())
216    }
217}