1mod filter;
16mod format;
17mod redaction;
18mod segment;
19mod sink;
20
21pub use segment::{prune_candidates, segment_day, segment_name, SegmentRetention};
22pub use sink::LineSink;
23
24use std::backtrace::Backtrace;
25use std::borrow::Cow;
26use std::collections::{HashMap, HashSet};
27use std::env;
28use std::fmt;
29use std::io::{self, Write};
30use std::panic;
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::sync::{Arc, Mutex, OnceLock};
34use std::time::SystemTime;
35
36use filter::LevelFilter as CkLogFilter;
37pub use format::{ParseError, ParsedLevel, ParsedLine};
38use redaction::fleet_redact;
39use segment::{SegmentDestination, SegmentNotice};
40use tracing::field::{Field, Visit};
41use tracing::span::{Attributes, Id, Record};
42use tracing::{Event, Metadata, Subscriber};
43pub use tracing_subscriber::filter::LevelFilter;
44use tracing_subscriber::layer::{Context, SubscriberExt};
45use tracing_subscriber::registry::LookupSpan;
46use tracing_subscriber::{Layer, Registry};
47
48static WRITE_FAILURE_REPORTED: AtomicBool = AtomicBool::new(false);
49static FILTER_FAILURE_REPORTED: AtomicBool = AtomicBool::new(false);
50
51#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub struct Retention {
57 pub max_file_mb: u32,
59 pub keep: u8,
61 pub max_age_days: u32,
63}
64
65impl Default for Retention {
66 fn default() -> Self {
67 Self {
68 max_file_mb: 32,
69 keep: 2,
70 max_age_days: 14,
71 }
72 }
73}
74
75impl Retention {
76 const TEST_BYTES_MARKER: u32 = 1 << 31;
77
78 #[doc(hidden)]
80 pub fn from_bytes_for_testing(max_file_bytes: u32, keep: u8, max_age_days: u32) -> Self {
81 assert!(max_file_bytes < Self::TEST_BYTES_MARKER);
82 Self {
83 max_file_mb: Self::TEST_BYTES_MARKER | max_file_bytes,
84 keep,
85 max_age_days,
86 }
87 }
88
89 pub(crate) fn max_bytes(self) -> u64 {
90 if self.max_file_mb & Self::TEST_BYTES_MARKER != 0 {
91 return u64::from(self.max_file_mb & !Self::TEST_BYTES_MARKER);
92 }
93
94 u64::from(self.max_file_mb) * 1024 * 1024
95 }
96}
97
98pub type Redactor = dyn for<'line> Fn(&'line str) -> Cow<'line, str> + Send + Sync;
100
101#[non_exhaustive]
124#[derive(Clone, Debug, Default)]
125pub struct Crates {
126 own: HashSet<String>,
127 ceilings: HashMap<String, Option<tracing::Level>>,
128}
129
130impl Crates {
131 pub fn new() -> Self {
133 Self::default()
134 }
135
136 pub fn own<I, S>(mut self, crate_names: I) -> Self
141 where
142 I: IntoIterator<Item = S>,
143 S: Into<String>,
144 {
145 self.own.extend(crate_names.into_iter().map(Into::into));
146 self
147 }
148
149 pub fn ceiling(mut self, crate_or_module: impl Into<String>, level: LevelFilter) -> Self {
161 let level = match level.to_string().to_ascii_lowercase().as_str() {
162 "off" => None,
163 "error" => Some(tracing::Level::ERROR),
164 "warn" => Some(tracing::Level::WARN),
165 "info" => Some(tracing::Level::INFO),
166 "debug" => Some(tracing::Level::DEBUG),
167 "trace" => Some(tracing::Level::TRACE),
168 _ => unreachable!("tracing level filters have a fixed set of levels"),
169 };
170 self.ceilings.insert(crate_or_module.into(), level);
171 self
172 }
173
174 fn ceiling_for(
175 &self,
176 mut module_path: &str,
177 dependency: bool,
178 ) -> Option<Option<tracing::Level>> {
179 if self.ceilings.is_empty() {
180 return None;
181 }
182 while let Some((parent, _)) = module_path.rsplit_once("::") {
183 if let Some(level) = self.ceilings.get(module_path) {
184 return Some(*level);
185 }
186 module_path = parent;
187 }
188 if dependency {
189 self.ceilings.get(module_path).copied()
190 } else {
191 None
192 }
193 }
194}
195
196pub struct Config {
198 pub module_id: String,
201 pub logs_dir: PathBuf,
207 pub bound: Vec<(String, String)>,
212 pub spec: Option<String>,
214 pub retention: SegmentRetention,
216 pub redactor: Option<Arc<Redactor>>,
218 pub clock: Option<Arc<dyn Fn() -> SystemTime + Send + Sync>>,
220}
221
222impl Config {
223 pub fn in_dir(module_id: &str, logs_dir: impl Into<PathBuf>) -> Self {
229 Self {
230 module_id: module_id.to_owned(),
231 logs_dir: logs_dir.into(),
232 bound: Vec::new(),
233 spec: None,
234 retention: SegmentRetention::default(),
235 redactor: None,
236 clock: None,
237 }
238 }
239
240 #[cfg(feature = "store-paths")]
244 pub fn for_module(module_id: &str) -> Self {
245 let data_dir = PathBuf::from(cortexkit_store_types::module_data_dir(module_id));
246 Self::in_dir(module_id, data_dir.join("logs"))
247 }
248
249 #[cfg(feature = "store-paths")]
252 pub fn for_plugin(module_id: &str, harness: &str) -> Self {
253 let mut config = Self::for_module(module_id);
254 config
255 .bound
256 .push(("harness".to_owned(), harness.to_owned()));
257 config
258 }
259
260 #[cfg(feature = "store-paths")]
267 pub fn from_env() -> Result<Self, InitError> {
268 let module_id = env::var("SUBC_MODULE_ID")
269 .ok()
270 .filter(|value| !value.is_empty())
271 .ok_or(InitError::ModuleIdNotInEnvironment)?;
272 let mut config = Self::for_module(&module_id);
273 if let Some(days) = env_u32("CK_LOG_MAX_AGE_DAYS") {
274 config.retention.max_age_days = days;
275 }
276 if let Some(mb) = env_u32("CK_LOG_ALARM_SEGMENT_MB") {
277 config.retention.alarm_segment_mb = mb;
278 }
279 Ok(config)
280 }
281}
282
283#[cfg(feature = "store-paths")]
284fn env_u32(name: &str) -> Option<u32> {
285 env::var(name).ok()?.trim().parse().ok()
286}
287
288#[derive(Clone)]
290pub struct Handle {
291 inner: Arc<LoggerInner>,
292}
293
294impl Handle {
295 pub fn swallowed_writes(&self) -> u64 {
297 self.inner.swallowed_writes.load(Ordering::Relaxed)
298 }
299
300 pub fn path(&self) -> PathBuf {
302 self.inner.path_now()
303 }
304
305 pub fn logs_dir(&self) -> &Path {
307 &self.inner.logs_dir
308 }
309
310 pub fn fallback_active(&self) -> bool {
312 self.inner.fallback_active
313 }
314
315 pub fn emit_at(
326 &self,
327 at: SystemTime,
328 level: tracing::Level,
329 logger: &str,
330 message: &str,
331 fields: &[(String, String)],
332 ) {
333 self.inner.emit_at(at, &level, logger, &[], message, fields);
334 }
335
336 pub fn emit_at_with_bound(
344 &self,
345 at: SystemTime,
346 level: tracing::Level,
347 logger: &str,
348 bound: &[(String, String)],
349 message: &str,
350 fields: &[(String, String)],
351 ) {
352 self.inner
353 .emit_at(at, &level, logger, bound, message, fields);
354 }
355
356 pub fn install_panic_hook(&self) {
363 install_panic_hook(Arc::clone(&self.inner));
364 }
365}
366
367static INSTALLED: OnceLock<Handle> = OnceLock::new();
372
373pub fn installed() -> Option<Handle> {
375 INSTALLED.get().cloned()
376}
377
378#[derive(Clone, Debug, Eq, PartialEq)]
380pub enum InitError {
381 ModuleIdNotInEnvironment,
384 GlobalSubscriberAlreadySet,
386}
387
388impl fmt::Display for InitError {
389 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
390 match self {
391 Self::ModuleIdNotInEnvironment => formatter.write_str(
392 "SUBC_MODULE_ID is not set; use Config::for_module(<id>) outside supervision",
393 ),
394 Self::GlobalSubscriberAlreadySet => {
395 formatter.write_str("a global tracing subscriber is already installed")
396 }
397 }
398 }
399}
400
401impl std::error::Error for InitError {}
402
403pub fn init(config: Config) -> Result<Handle, InitError> {
405 init_inner(config, None)
406}
407
408pub fn init_with_crates(config: Config, crates: Crates) -> Result<Handle, InitError> {
410 init_inner(config, Some(crates))
411}
412
413fn init_inner(config: Config, crates: Option<Crates>) -> Result<Handle, InitError> {
414 let (layer, handle) = build_layer(config, Box::new(io::stderr()), false, crates)?;
415 let panic_inner = Arc::clone(&handle.inner);
416 let subscriber = Registry::default().with(layer);
417 tracing::subscriber::set_global_default(subscriber)
418 .map_err(|_| InitError::GlobalSubscriberAlreadySet)?;
419 install_panic_hook(panic_inner);
420 let _ = INSTALLED.set(handle.clone());
421 Ok(handle)
422}
423
424pub fn layer(config: Config) -> Result<(LogLayer, Handle), InitError> {
429 build_layer(config, Box::new(io::stderr()), false, None)
430}
431
432pub fn layer_with_stderr_copy(config: Config) -> Result<(LogLayer, Handle), InitError> {
439 build_layer(config, Box::new(io::stderr()), true, None)
440}
441
442#[cfg(feature = "store-paths")]
444pub fn init_from_env() -> Result<Handle, InitError> {
445 init(Config::from_env()?)
446}
447
448#[cfg(feature = "store-paths")]
450pub fn init_from_env_with_crates(crates: Crates) -> Result<Handle, InitError> {
451 init_with_crates(Config::from_env()?, crates)
452}
453
454pub fn session_span(issuer: &str, id: &str) -> tracing::Span {
457 if issuer.is_empty() || id.is_empty() {
461 tracing::Span::none()
462 } else {
463 let session = format!("{issuer}:{id}");
464 tracing::info_span!("cortexkit.session", session = %session)
465 }
466}
467
468pub fn parse_line(line: &str) -> Result<ParsedLine<'_>, ParseError> {
470 format::parse(line)
471}
472
473struct LoggerInner {
474 module_id: String,
475 logs_dir: PathBuf,
476 process_bound: Vec<(String, String)>,
477 destination: Mutex<Option<SegmentDestination>>,
478 stderr: Mutex<Box<dyn Write + Send>>,
479 swallowed_writes: AtomicU64,
480 fallback_active: bool,
481 stderr_copy: bool,
482 redactor: Option<Arc<Redactor>>,
483 clock: Arc<dyn Fn() -> SystemTime + Send + Sync>,
484}
485
486impl LoggerInner {
487 fn path_now(&self) -> PathBuf {
488 self.logs_dir
489 .join(segment::segment_name(&self.module_id, (self.clock)()))
490 }
491
492 fn emit(
493 &self,
494 level: &tracing::Level,
495 logger: &str,
496 scoped_bound: &[(String, String)],
497 message: &str,
498 fields: &[(String, String)],
499 ) {
500 self.emit_at((self.clock)(), level, logger, scoped_bound, message, fields);
501 }
502
503 fn emit_at(
504 &self,
505 at: SystemTime,
506 level: &tracing::Level,
507 logger: &str,
508 scoped_bound: &[(String, String)],
509 message: &str,
510 fields: &[(String, String)],
511 ) {
512 let mut bound: Vec<(String, String)> = self.process_bound.clone();
516 for (key, value) in scoped_bound {
517 match bound.iter_mut().find(|(existing, _)| existing == key) {
518 Some(slot) => slot.1 = value.clone(),
519 None => bound.push((key.clone(), value.clone())),
520 }
521 }
522 let raw = format::render_line(at, level, logger, &bound, message, fields);
523 let fleet_redacted = fleet_redact(&raw);
524 let module_redacted = self.redactor.as_ref().map_or_else(
525 || Cow::Borrowed(fleet_redacted.as_ref()),
526 |redactor| redactor(&fleet_redacted),
527 );
528 let guarded = format::escape_raw_controls(&module_redacted);
533 self.write_line(&guarded, at);
534 }
535
536 fn write_line(&self, line: &str, at: SystemTime) {
537 let mut bytes = Vec::with_capacity(line.len() + 1);
538 bytes.extend_from_slice(line.as_bytes());
539 bytes.push(b'\n');
540
541 let result = {
545 let mut destination = self
546 .destination
547 .lock()
548 .unwrap_or_else(std::sync::PoisonError::into_inner);
549 match destination.as_mut() {
550 None => {
551 let mut stderr = self
552 .stderr
553 .lock()
554 .unwrap_or_else(std::sync::PoisonError::into_inner);
555 stderr.write_all(&bytes).map(|()| None)
556 }
557 Some(segment) => {
558 let written = segment.write(&bytes, at);
559 if self.stderr_copy && written.is_ok() {
560 let mut stderr = self
561 .stderr
562 .lock()
563 .unwrap_or_else(std::sync::PoisonError::into_inner);
564 let _ = stderr.write_all(&bytes);
565 }
566 written
567 }
568 }
569 };
570
571 match result {
572 Ok(None) => {}
573 Ok(Some(notice)) => self.report_notice(notice),
574 Err(error) => {
575 self.swallowed_writes.fetch_add(1, Ordering::Relaxed);
576 if !WRITE_FAILURE_REPORTED.swap(true, Ordering::Relaxed) {
577 self.report(&format!(
578 "cortexkit-log: log write failed; future failures will be swallowed: {error}\n"
579 ));
580 }
581 }
582 }
583 }
584
585 fn report_notice(&self, notice: SegmentNotice) {
590 match notice {
591 SegmentNotice::Pruned { removed, kept } => self.report(&format!(
592 "cortexkit-log: {}.retention pruned={removed} kept={kept}\n",
593 self.module_id
594 )),
595 SegmentNotice::Oversized { path, bytes } => self.report(&format!(
596 "cortexkit-log: segment oversized, NOT truncated: path={} bytes={bytes}\n",
597 path.display()
598 )),
599 }
600 }
601
602 fn report(&self, report: &str) {
603 let mut stderr = self
604 .stderr
605 .lock()
606 .unwrap_or_else(std::sync::PoisonError::into_inner);
607 let _ = stderr.write_all(report.as_bytes());
608 }
609
610 fn write_panic(&self, information: &panic::PanicHookInfo<'_>) {
611 let at = (self.clock)();
612 let logger = format!("{}.panic", self.module_id);
613 let panic_text = information.to_string();
614 for line in panic_text.lines() {
615 self.emit_at(at, &tracing::Level::ERROR, &logger, &[], line, &[]);
616 }
617 let backtrace = Backtrace::force_capture().to_string();
618 for line in backtrace.lines() {
619 self.emit_at(at, &tracing::Level::ERROR, &logger, &[], line, &[]);
620 }
621 }
622}
623
624pub struct LogLayer {
627 inner: Arc<LoggerInner>,
628 filter: CkLogFilter,
629 crates: Option<Crates>,
630}
631
632impl LogLayer {
633 pub fn with_crates(mut self, crates: Crates) -> Self {
638 self.crates = Some(crates);
639 self
640 }
641
642 fn event_path<'a>(&self, metadata: &'a Metadata<'_>) -> format::LoggerPath<'a> {
643 let Some(crates) = &self.crates else {
644 return format::LoggerPath::from_target(&self.inner.module_id, metadata.target());
645 };
646
647 let module_path = metadata.module_path().unwrap_or(metadata.target());
648 let crate_name = module_path.split("::").next().unwrap_or(module_path);
649 if crates.own.contains(crate_name) {
650 return format::LoggerPath::from_target(&self.inner.module_id, metadata.target());
651 }
652
653 format::LoggerPath::dependency(crate_name)
654 }
655
656 fn metadata_enabled(&self, metadata: &Metadata<'_>) -> bool {
657 if metadata.is_span() {
658 return true;
659 }
660 let path = self.event_path(metadata);
661 self.event_enabled(metadata, path)
662 }
663
664 fn event_enabled(&self, metadata: &Metadata<'_>, path: format::LoggerPath<'_>) -> bool {
665 let ceiling = self.crates.as_ref().and_then(|crates| {
666 crates.ceiling_for(
667 metadata.module_path().unwrap_or(metadata.target()),
668 path.dependency_name().is_some(),
669 )
670 });
671 self.filter
672 .enabled_path(&self.inner.module_id, path, metadata.level(), ceiling)
673 }
674}
675
676impl<S> Layer<S> for LogLayer
677where
678 S: Subscriber + for<'lookup> LookupSpan<'lookup>,
679{
680 fn register_callsite(
681 &self,
682 metadata: &'static Metadata<'static>,
683 ) -> tracing::subscriber::Interest {
684 if !metadata.is_event() || self.metadata_enabled(metadata) {
685 tracing::subscriber::Interest::always()
686 } else {
687 tracing::subscriber::Interest::never()
688 }
689 }
690
691 fn max_level_hint(&self) -> Option<LevelFilter> {
692 let own_crates_possible = self
693 .crates
694 .as_ref()
695 .is_none_or(|crates| !crates.own.is_empty());
696 let level = self.filter.max_level_hint(
697 &self.inner.module_id,
698 own_crates_possible,
699 self.crates.as_ref().map(|crates| &crates.ceilings),
700 );
701 Some(level.map_or(LevelFilter::OFF, LevelFilter::from_level))
702 }
703
704 fn enabled(&self, metadata: &Metadata<'_>, _context: Context<'_, S>) -> bool {
705 self.metadata_enabled(metadata)
706 }
707
708 fn on_new_span(&self, attributes: &Attributes<'_>, id: &Id, context: Context<'_, S>) {
709 let mut visitor = BoundVisitor::default();
710 attributes.record(&mut visitor);
711 if let (false, Some(span)) = (visitor.bound.is_empty(), context.span(id)) {
712 span.extensions_mut().insert(SpanBound(visitor.bound));
713 }
714 }
715
716 fn on_record(&self, id: &Id, values: &Record<'_>, context: Context<'_, S>) {
717 let mut visitor = BoundVisitor::default();
718 values.record(&mut visitor);
719 if let (false, Some(span)) = (visitor.bound.is_empty(), context.span(id)) {
720 let mut extensions = span.extensions_mut();
721 match extensions.get_mut::<SpanBound>() {
722 Some(existing) => existing.0.extend(visitor.bound),
723 None => extensions.insert(SpanBound(visitor.bound)),
724 }
725 }
726 }
727
728 fn on_event(&self, event: &Event<'_>, context: Context<'_, S>) {
729 let metadata = event.metadata();
730 let path = self.event_path(metadata);
731 if !self.event_enabled(metadata, path) {
732 return;
733 }
734 let logger = path.logger_name(&self.inner.module_id);
735
736 let mut visitor = EventVisitor::default();
737 event.record(&mut visitor);
738 let mut scoped: Vec<(String, String)> = Vec::new();
743 if let Some(scope) = context.event_scope(event) {
744 for span in scope.from_root() {
745 if let Some(bound) = span.extensions().get::<SpanBound>() {
746 for (key, value) in &bound.0 {
747 match scoped.iter_mut().find(|(existing, _)| existing == key) {
748 Some(slot) => slot.1 = value.clone(),
749 None => scoped.push((key.clone(), value.clone())),
750 }
751 }
752 }
753 }
754 }
755 self.inner.emit(
756 metadata.level(),
757 &logger,
758 &scoped,
759 visitor.message.as_deref().unwrap_or(""),
760 &visitor.fields,
761 );
762 }
763}
764
765#[derive(Clone)]
766struct SpanBound(Vec<(String, String)>);
767
768#[derive(Default)]
769struct BoundVisitor {
770 bound: Vec<(String, String)>,
771}
772
773impl BoundVisitor {
774 fn record(&mut self, field: &Field, value: String) {
775 if !value.is_empty() {
778 self.bound.push((field.name().to_owned(), value));
779 }
780 }
781}
782
783impl Visit for BoundVisitor {
784 fn record_str(&mut self, field: &Field, value: &str) {
785 self.record(field, value.to_owned());
786 }
787
788 fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
789 let rendered = format!("{value:?}");
790 let value = rendered
791 .strip_prefix('"')
792 .and_then(|unquoted| unquoted.strip_suffix('"'))
793 .unwrap_or(&rendered);
794 self.record(field, value.to_owned());
795 }
796
797 fn record_i64(&mut self, field: &Field, value: i64) {
798 self.record(field, value.to_string());
799 }
800
801 fn record_u64(&mut self, field: &Field, value: u64) {
802 self.record(field, value.to_string());
803 }
804
805 fn record_bool(&mut self, field: &Field, value: bool) {
806 self.record(field, value.to_string());
807 }
808}
809
810#[derive(Default)]
811struct EventVisitor {
812 message: Option<String>,
813 fields: Vec<(String, String)>,
814}
815
816impl EventVisitor {
817 fn record(&mut self, field: &Field, value: String) {
818 if field.name() == "message" {
819 self.message = Some(value);
820 } else {
821 self.fields.push((field.name().to_owned(), value));
822 }
823 }
824}
825
826impl Visit for EventVisitor {
827 fn record_f64(&mut self, field: &Field, value: f64) {
828 self.record(field, value.to_string());
829 }
830
831 fn record_i64(&mut self, field: &Field, value: i64) {
832 self.record(field, value.to_string());
833 }
834
835 fn record_u64(&mut self, field: &Field, value: u64) {
836 self.record(field, value.to_string());
837 }
838
839 fn record_i128(&mut self, field: &Field, value: i128) {
840 self.record(field, value.to_string());
841 }
842
843 fn record_u128(&mut self, field: &Field, value: u128) {
844 self.record(field, value.to_string());
845 }
846
847 fn record_bool(&mut self, field: &Field, value: bool) {
848 self.record(field, value.to_string());
849 }
850
851 fn record_str(&mut self, field: &Field, value: &str) {
852 self.record(field, value.to_owned());
853 }
854
855 fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
856 self.record(field, value.to_string());
857 }
858
859 fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
860 self.record(field, format!("{value:?}"));
861 }
862}
863
864fn build_layer(
865 config: Config,
866 stderr: Box<dyn Write + Send>,
867 stderr_copy: bool,
868 crates: Option<Crates>,
869) -> Result<(LogLayer, Handle), InitError> {
870 let clock = config.clock.unwrap_or_else(|| Arc::new(SystemTime::now));
871 let now = clock();
872 let (destination, open_notice, open_error) = match SegmentDestination::open(
873 &config.logs_dir,
874 &config.module_id,
875 config.retention,
876 now,
877 true,
878 ) {
879 Ok((destination, notice)) => (Some(destination), notice, None),
880 Err(error) => (None, None, Some(error)),
881 };
882 let fallback_active = open_error.is_some();
883 let inner = Arc::new(LoggerInner {
884 module_id: config.module_id,
885 logs_dir: config.logs_dir,
886 process_bound: config.bound,
887 destination: Mutex::new(destination),
888 stderr: Mutex::new(stderr),
889 swallowed_writes: AtomicU64::new(0),
890 fallback_active,
891 stderr_copy,
892 redactor: config.redactor,
893 clock,
894 });
895
896 if let Some(notice) = open_notice {
897 inner.report_notice(notice);
898 }
899 if let Some(error) = open_error {
900 let logger = inner.module_id.clone();
901 inner.emit(
902 &tracing::Level::ERROR,
903 &logger,
904 &[],
905 "log directory unavailable; falling back to stderr",
906 &[
907 ("dir".to_owned(), inner.logs_dir.display().to_string()),
908 ("error".to_owned(), error.to_string()),
909 ],
910 );
911 }
912
913 let filter = make_filter(config.spec, &inner);
914 let layer = LogLayer {
915 inner: Arc::clone(&inner),
916 filter,
917 crates,
918 };
919 Ok((layer, Handle { inner }))
920}
921
922fn make_filter(spec_override: Option<String>, inner: &LoggerInner) -> CkLogFilter {
923 let spec = spec_override.or_else(|| env::var("CK_LOG").ok());
924 let spec = spec
925 .as_deref()
926 .map(str::trim)
927 .filter(|value| !value.is_empty());
928 match spec {
929 Some(spec) => CkLogFilter::parse(spec).unwrap_or_else(|error| {
930 if !FILTER_FAILURE_REPORTED.swap(true, Ordering::Relaxed) {
931 inner.report(&format!(
932 "cortexkit-log: invalid CK_LOG value {spec:?}; using info: {error}\n"
933 ));
934 }
935 CkLogFilter::info()
936 }),
937 None => CkLogFilter::info(),
938 }
939}
940
941fn install_panic_hook(inner: Arc<LoggerInner>) {
942 let previous = panic::take_hook();
943 panic::set_hook(Box::new(move |information| {
944 inner.write_panic(information);
945 previous(information);
946 }));
947}
948
949#[cfg(test)]
950mod tests;