Skip to content

Commit 55b6c35

Browse files
committed
OXY-1516: support stderr as a log output target
This commit adds support for writing logs to stderr. For non-daemonized processes, think CLIs or short-lived tests, its useful to have a separate output stream for our logs.
1 parent 251d193 commit 55b6c35

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

foundations/src/telemetry/log/init.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,15 +77,23 @@ pub(crate) fn init(service_info: &ServiceInfo, settings: &LoggingSettings) -> Bo
7777
const CHANNEL_SIZE: usize = 1024;
7878

7979
let async_drain = match (&settings.output, &settings.format) {
80-
(LogOutput::Terminal, LogFormat::Text) => {
81-
let drain = TextDrain::new(TermDecorator::new().stdout().build())
82-
.build()
83-
.fuse();
80+
(output @ (LogOutput::Terminal | LogOutput::Stderr), LogFormat::Text) => {
81+
let decorator = if matches!(output, LogOutput::Terminal) {
82+
TermDecorator::new().stdout().build()
83+
} else {
84+
TermDecorator::new().stderr().build()
85+
};
86+
87+
let drain = TextDrain::new(decorator).build().fuse();
8488
AsyncDrain::new(drain).chan_size(CHANNEL_SIZE).build()
8589
}
86-
(LogOutput::Terminal, LogFormat::Json) => {
87-
let stdout_writer = stdout_writer_without_line_buffering();
88-
let drain = build_json_log_drain(stdout_writer);
90+
(output @ (LogOutput::Terminal | LogOutput::Stderr), LogFormat::Json) => {
91+
let writer = if matches!(output, LogOutput::Terminal) {
92+
stdout_writer_without_line_buffering()
93+
} else {
94+
stderr_writer_without_line_buffering()
95+
};
96+
let drain = build_json_log_drain(writer);
8997
AsyncDrain::new(drain).chan_size(CHANNEL_SIZE).build()
9098
}
9199
(LogOutput::File(file), LogFormat::Text) => {
@@ -133,6 +141,12 @@ fn stdout_writer_without_line_buffering() -> BufWriter<File> {
133141
BufWriter::with_capacity(BUF_SIZE, stdout)
134142
}
135143

144+
/// Opens fd 2 directly and wraps with a [`BufWriter`] with [`BUF_SIZE`] capacity.
145+
fn stderr_writer_without_line_buffering() -> BufWriter<File> {
146+
let stderr = unsafe { File::from_raw_fd(2) };
147+
BufWriter::with_capacity(BUF_SIZE, stderr)
148+
}
149+
136150
fn get_root_drain(
137151
_settings: &LoggingSettings,
138152
base_drain: Arc<dyn SendSyncRefUnwindSafeDrain<Err = Never, Ok = ()> + 'static>,

foundations/src/telemetry/settings/logging.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ pub enum LogOutput {
4545
/// Write log to terminal.
4646
#[default]
4747
Terminal,
48+
/// Write log to [`std::io::Stderr`].
49+
Stderr,
4850
/// Write log to file with the specified path.
4951
///
5052
/// File will be created if it doesn't exist and overwritten otherwise.

0 commit comments

Comments
 (0)