1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use File;
use ;
use Arc;
use Ordering;
use Record;
use crate::;
// ═════════════════════════════════════════════════════════════════════════════
// UNIX: LogFile — bare File, no Mutex
// ═════════════════════════════════════════════════════════════════════════════
/// An open log file used for `O_APPEND` writes on Unix.
///
/// Wrapped in an `Arc` that is shared by all thread-local `BufWriter<FileWriter>`
/// instances currently pointing at this file. The `Arc` pointer identity is the
/// rotation detector: a mismatch between a thread's cached pointer and the
/// logger's current pointer means the file was rotated since that thread last logged.
pub
// ═════════════════════════════════════════════════════════════════════════════
// WINDOWS: LogFile — Mutex<File>
// ═════════════════════════════════════════════════════════════════════════════
use Mutex;
/// An open log file used for serialised writes on Windows.
///
/// The inner `Mutex<File>` serialises concurrent `WriteFile` calls because
/// Windows does not provide the `O_APPEND` atomicity guarantee that Unix does.
/// The mutex is held only for the duration of each `WriteFile` syscall;
/// all formatting work occurs in the per-thread `BufWriter` beforehand.
pub
// ═════════════════════════════════════════════════════════════════════════════
// COMMON + PLATFORM: FileWriter — the W in BufWriter<W>
//
// This is the only platform-diverging type visible to the BufWriter.
// BufWriter calls FileWriter::write() when its internal buffer is full
// or when flush() is called. BufWriter calls FileWriter::flush() after
// the data write — our impl is a no-op because the data is already in
// the kernel page cache after write().
//
// UNIX path (no lock):
// write() → (&self.0.file).write(buf)
// O_APPEND guarantees this write() syscall is atomic — no two threads'
// bytes interleave regardless of concurrency.
//
// WINDOWS path (Mutex held only for the syscall):
// write() → Mutex<File>::lock() → file.write(buf) → unlock
// The lock is held only for the duration of WriteFile().
// All formatting happened inside BufWriter's internal buffer before
// write() was even called — formatting is always lock-free.
//
// Why BufWriter::flush() calling FileWriter::flush() is a no-op:
// BufWriter::flush() first calls inner.write(buffered_bytes) to drain
// its buffer, then calls inner.flush() to propagate the flush.
// Our write() already delivered the bytes to the kernel (Unix) or to
// the file (Windows via WriteFile). There is nothing left to flush at
// the FileWriter level. The kernel's own writeback handles disk I/O.
// ═════════════════════════════════════════════════════════════════════════════
/// The `W` in `BufWriter<W>` — bridges the per-thread buffer to a shared [`LogFile`].
///
/// Holds an `Arc<LogFile>` that doubles as a rotation detector: on every log
/// call, `write_record` compares this pointer with the logger's current `Arc`
/// via [`Arc::ptr_eq`]. A mismatch means the file was rotated since this thread
/// last logged, and the old buffer is flushed to the old file before switching.
pub );
// ═════════════════════════════════════════════════════════════════════════════
// COMMON: Thread-local BufWriter
//
// Each thread owns a `BufWriter<FileWriter>`.
// `FileWriter` holds an `Arc<LogFile>` — used for both writing and rotation
// detection (Arc::ptr_eq).
//
// Lifecycle
// ─────────
// First log call : `None` → `Some(BufWriter::with_capacity(…))`
// One heap allocation: BufWriter's internal byte buffer.
// Normal log call : writeln! into BufWriter's internal buffer — zero alloc.
// BufWriter flushes automatically when buffer is full.
// Periodic flush : FLUSH_FLAG seen → bw.flush() — no alloc.
// Rotation : Arc::ptr_eq mismatch → bw.flush() (old file) → replace.
// Thread exit : BufWriter::drop() calls flush() automatically.
// No custom Drop impl needed — stdlib handles it.
//
// Why BufWriter::drop() replacing ThreadBuf::drop() is correct
// ─────────────────────────────────────────────────────────────
// BufWriter<W>::drop() calls self.flush() which calls W::write(buffered_bytes).
// FileWriter::write() delivers bytes to the kernel (Unix) or acquires the
// Mutex and calls WriteFile() (Windows). The effect is implemented by the
// stdlib with no code on our side.
//
// The one caveat: if flush() fails inside drop(), the error is silently
// discarded. This matches the behaviour of most I/O types in Rust and is
// acceptable for a logger (the process is exiting anyway).
// ═════════════════════════════════════════════════════════════════════════════
thread_local!
/// Invoke `f` with the calling thread's `BufWriter`, if one has been initialised.
///
/// Does nothing when the thread has not yet emitted any log records.
pub
// ═════════════════════════════════════════════════════════════════════════════
// COMMON: write_record
//
// Hot path breakdown (steady state — no rotation, no flush flag):
//
// Arc::ptr_eq() 1 pointer compare — branch not taken
// FLUSH_FLAG.swap() 1 atomic op — false, branch not taken
// writeln!(bw, …) extend_from_slice into BufWriter's Vec<u8>
// zero allocation while buffer has capacity
// BufWriter internal check if len >= capacity → FileWriter::write()
// one write() syscall per buffer-full event
//
// Rotation path (Arc mismatch detected):
// bw.flush() FileWriter::write(remaining bytes) to OLD file
// drop old BufWriter BufWriter::drop() — another flush (no-op, already empty)
// BufWriter::with_capacity one heap allocation: new internal byte buffer
// writeln!(bw, …) first write into new buffer
//
// `current: Arc<LogFile>` is cloned from ArcSwapOption::load_full() in Log::log().
// load_full() increments the Arc refcount (atomic inc, ~1 ns, no heap alloc).
// The Arc is either stored in the new BufWriter (rotation) or dropped at the
// end of write_record (steady state, atomic dec, ~1 ns).
// ═════════════════════════════════════════════════════════════════════════════
/// Write a single log `record` to the calling thread's `BufWriter`.
///
/// Handles three concerns in sequence:
/// 1. **Rotation detection** — if the thread's cached `Arc<LogFile>` no longer
/// matches the logger's current pointer, the old writer is flushed and
/// replaced with a fresh one pointing to the new file.
/// 2. **Periodic flush** — if `FLUSH_FLAG` is set by the background worker, the
/// buffer is flushed before appending the new record.
/// 3. **Write** — the rendered record bytes are appended to the buffer.
pub