logwise 0.3.0

an opinionated logging library for Rust
Documentation
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
//SPDX-License-Identifier: MIT OR Apache-2.0
/*!
# Context Management

This module provides logwise's thread-local context system that enables hierarchical,
task-based logging with automatic lifecycle management and performance tracking.

## Overview

The context system is built around two main concepts:

1. **Tasks** - Logical units of work that can have performance statistics tracked and
   automatic lifecycle logging
2. **Contexts** - Thread-local hierarchical containers that can define new tasks or
   inherit from parent contexts

## Key Features

- **Hierarchical Context Management**: Contexts can have parent-child relationships
  that are reflected in log output indentation
- **Task-based Logging**: Each context is associated with a task that provides
  structured logging with automatic start/finish messages
- **Performance Interval Tracking**: Tasks can accumulate performance statistics
  that are automatically logged when the task completes
- **Trace Support**: Contexts can enable tracing mode for detailed debugging
- **Async Executor Integration**: The [`ApplyContext`] wrapper ensures proper
  context propagation in hostile async executors

## Basic Usage

```rust
use logwise::context::Context;

// Create a new task context
let parent_context = Context::current();
let task_context = Context::new_task(Some(parent_context), "my_task".to_string());
task_context.set_current();

// Use logwise macros - they will automatically include task information
logwise::info_sync!("Task started");

// Create a child context that inherits the task
let child_context = Context::from_parent(Context::current());
child_context.set_current();

logwise::info_sync!("Child operation");
// When contexts are dropped, tasks log completion statistics
```

## Context Types

There are two ways to create contexts:

- [`Context::new_task()`]: Creates a new task with its own lifecycle and statistics
- [`Context::from_parent()`]: Creates a context that inherits the parent's task

## Async Usage

For async code where executors may not preserve thread-local state:

```rust
use logwise::context::{Context, ApplyContext};

let context = Context::current();
let future = async {
    logwise::info_sync!("Inside async block");
    // async work here
};

// Wrap the future to ensure context is applied during polling
let wrapped_future = ApplyContext::new(context, future);
// Execute wrapped_future with your async runtime
```

## Performance Tracking

Tasks automatically collect performance interval statistics from the `perfwarn!` macro
and log them when the task completes. This provides automatic performance monitoring
without explicit instrumentation.

## Thread Safety

The context system is thread-local - each thread maintains its own context stack.
When spawning new threads or using async executors, you should explicitly propagate
contexts using [`ApplyContext`] or by setting contexts in the new execution context.
*/
use crate::Level;
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::Display;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::task::Poll;

static TASK_ID: AtomicU64 = AtomicU64::new(0);

static CONTEXT_ID: AtomicU64 = AtomicU64::new(0);

/// Unique identifier for a task within the logging system.
///
/// Each task gets a unique ID that is included in all log messages to help
/// correlate related log entries. Task IDs are monotonically increasing
/// and thread-safe.
///
/// # Examples
///
/// ```rust
/// use logwise::context::Context;
///
/// let context = Context::new_task(None, "example".to_string());
/// let task_id = context.task_id();
/// println!("Task ID: {}", task_id);
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct TaskID(u64);

impl Display for TaskID {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Unique identifier for a context within the logging system.
///
/// Each context gets a unique ID that can be used for context management
/// operations like [`Context::pop()`]. Context IDs are monotonically
/// increasing and thread-safe.
///
/// # Examples
///
/// ```rust
/// use logwise::context::Context;
///
/// let context = Context::current();
/// let context_id = context.context_id();
/// // Save the ID to pop back to this context later
/// # let child_context = Context::from_parent(context);
/// # child_context.set_current();
/// // ... do work in child context ...
/// Context::pop(context_id);
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ContextID(u64);

impl Task {
    #[inline]
    fn add_task_interval(&self, key: &'static str, duration: crate::sys::Duration) {
        let mut borrow = self.mutable.lock().unwrap();
        borrow
            .interval_statistics
            .get_mut(key)
            .map(|v| *v += duration)
            .unwrap_or_else(|| {
                borrow.interval_statistics.insert(key, duration);
            });
    }
}

impl Drop for Task {
    fn drop(&mut self) {
        if !self.mutable.lock().unwrap().interval_statistics.is_empty() {
            let mut record = crate::log_record::LogRecord::new(Level::PerfWarn);
            //log task ID
            record.log_owned(format!("{} ", self.task_id.0));
            record.log("PERFWARN: statistics[");
            for (key, duration) in &self.mutable.lock().unwrap().interval_statistics {
                record.log(key);
                record.log_owned(format!(": {:?},", duration));
            }
            record.log("]");
            let global_loggers = crate::global_logger::global_loggers();
            for logger in global_loggers {
                logger.finish_log_record(record.clone());
            }
        }

        if self.label != "Default task" {
            let mut record = crate::log_record::LogRecord::new(Level::Info);
            record.log_owned(format!("{} ", self.task_id.0));
            record.log("Finished task `");
            record.log(&self.label);
            record.log("`");
            let global_loggers = crate::global_logger::global_loggers();
            for logger in global_loggers {
                logger.finish_log_record(record.clone());
            }
        }
    }
}
#[derive(Clone, Debug)]
struct TaskMutable {
    interval_statistics: HashMap<&'static str, crate::sys::Duration>,
}

/// Represents a logical unit of work within the logging system.
///
/// Tasks provide structured logging with automatic lifecycle management and
/// performance statistics collection. Each task has a unique ID and a
/// human-readable label for identification in logs.
///
/// Tasks automatically log their completion when dropped, along with any
/// accumulated performance statistics from `perfwarn!` macro usage.
///
/// # Performance Tracking
///
/// Tasks collect performance interval statistics from the `perfwarn!` macro.
/// When the task is dropped, these statistics are automatically logged as
/// a performance warning, providing visibility into timing bottlenecks.
///
/// # Lifecycle Logging
///
/// Tasks with labels other than "Default task" automatically log a completion
/// message when dropped, helping track the execution flow of complex operations.
///
/// # Examples
///
/// Tasks are typically created through [`Context::new_task()`] rather than directly:
///
/// ```rust
/// use logwise::context::Context;
///
/// // Create a context with a new task
/// let context = Context::new_task(None, "data_processing".to_string());
/// context.set_current();
///
/// // The task ID is now included in all log messages
/// logwise::info_sync!("Starting data processing");
///
/// // When the context/task is dropped, completion is logged
/// // along with any accumulated performance statistics
/// ```
#[derive(Debug)]
pub struct Task {
    task_id: TaskID,
    mutable: Mutex<TaskMutable>,
    label: String,
}

impl Task {
    fn new(label: String) -> Task {
        Task {
            task_id: TaskID(TASK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)),
            mutable: Mutex::new(TaskMutable {
                interval_statistics: HashMap::new(),
            }),
            label,
        }
    }
}

/// Internal context data shared between cloned contexts.
///
/// This structure contains the actual context state and is wrapped in an Arc
/// to allow for efficient cloning of contexts while sharing the same underlying data.
#[derive(Debug)]
struct ContextInner {
    parent: Option<Context>,
    context_id: u64,
    /// If Some, this context defines a new task. If None, the task is inherited from the parent.
    define_task: Option<Task>,
    /// Whether this context is currently in tracing mode for detailed debugging.
    is_tracing: AtomicBool,
}

/// A hierarchical, thread-local context for structured logging.
///
/// Context provides task-based logging with automatic lifecycle management,
/// performance tracking, and hierarchical organization. Each context is
/// associated with either its own task or inherits a task from its parent.
///
/// # Context Hierarchy
///
/// Contexts form a parent-child hierarchy that is reflected in log output
/// through indentation. Child contexts can either:
/// - Define a new task (via [`Context::new_task()`])
/// - Inherit the parent's task (via [`Context::from_parent()`])
///
/// # Thread-Local Storage
///
/// The current context is stored in thread-local storage and automatically
/// used by all logwise macros. Use [`Context::current()`] to get the current
/// context and [`Context::set_current()`] to change it.
///
/// # Examples
///
/// ## Basic Task Creation
///
/// ```rust
/// use logwise::context::Context;
///
/// // Get current context (starts with default task)
/// let parent = Context::current();
///
/// // Create a new task context
/// let task_context = Context::new_task(Some(parent), "my_operation".to_string());
/// task_context.set_current();
///
/// // All logging now includes this task's information
/// logwise::info_sync!("Operation started");
/// ```
///
/// ## Context Inheritance
///
/// ```rust
/// use logwise::context::Context;
///
/// let task_context = Context::new_task(None, "parent_task".to_string());
/// task_context.set_current();
///
/// // Create child that inherits the same task but adds hierarchy
/// let child_context = Context::from_parent(Context::current());
/// child_context.set_current();
///
/// // Logs will show increased indentation but same task ID
/// logwise::info_sync!("Child operation");
/// ```
///
/// ## Context Stack Management
///
/// ```rust
/// use logwise::context::Context;
///
/// let original = Context::current();
/// let child = Context::from_parent(original.clone());
/// let child_id = child.context_id();
/// child.set_current();
///
/// // ... do work in child context ...
///
/// // Pop back to original context
/// Context::pop(child_id);
/// assert_eq!(Context::current(), original);
/// ```
#[derive(Debug, Clone)]
pub struct Context {
    inner: Arc<ContextInner>,
}

impl PartialEq for Context {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl Eq for Context {}

impl Hash for Context {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Arc::as_ptr(&self.inner).hash(state);
    }
}

impl Display for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let nesting = self.nesting_level();
        write!(
            f,
            "{}{} ({})",
            "  ".repeat(nesting),
            self.task_id(),
            self.task().label
        )
    }
}

impl AsRef<Task> for Context {
    fn as_ref(&self) -> &Task {
        self.task()
    }
}

thread_local! {
    static CONTEXT: Cell<Context> = Cell::new(Context::new_task_internal(None,"Default task".to_string(),0));
}

impl Context {
    /// Returns the current thread-local context.
    ///
    /// This function provides access to the context that is currently active
    /// on this thread. All logwise macros use this context automatically.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let current_context = Context::current();
    /// println!("Current task ID: {}", current_context.task_id());
    /// ```
    #[inline]
    pub fn current() -> Context {
        CONTEXT.with(|c|
            //safety: we don't let anyone get a mutable reference to this
            unsafe{&*c.as_ptr()}.clone())
    }

    /// Returns a reference to the task associated with this context.
    ///
    /// If this context defines its own task, that task is returned. Otherwise,
    /// the task is inherited from the parent context by walking up the hierarchy.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let context = Context::new_task(None, "example_task".to_string());
    /// let task = context.task();
    /// 
    /// // The task reference provides access to the underlying task
    /// // We can verify it's the same task by using it in context operations
    /// let task_id = context.task_id();
    /// assert_eq!(task_id, context.task_id()); // Should be identical
    /// ```
    pub fn task(&self) -> &Task {
        if let Some(task) = &self.inner.define_task {
            task
        } else {
            self.inner
                .parent
                .as_ref()
                .expect("No parent context")
                .task()
        }
    }

    /// Creates a new context with its own task.
    ///
    /// This creates a context that defines a new task with its own lifecycle
    /// and performance tracking. The task will log completion messages and
    /// statistics when dropped.
    ///
    /// # Parameters
    /// * `parent` - The parent context. If `None`, this context will be orphaned
    ///   and have no hierarchical relationship.
    /// * `label` - A human-readable label for the task, used in log messages.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// // Create a root task
    /// let root_task = Context::new_task(None, "root_operation".to_string());
    /// let root_task_id = root_task.task_id();
    /// root_task.set_current();
    ///
    /// // Create a child task
    /// let child_task = Context::new_task(
    ///     Some(Context::current()),
    ///     "child_operation".to_string()
    /// );
    /// let child_task_id = child_task.task_id();
    /// child_task.set_current();
    ///
    /// // Both contexts will have different task IDs
    /// assert_ne!(root_task_id, child_task_id);
    /// ```
    #[inline]
    pub fn new_task(parent: Option<Context>, label: String) -> Context {
        let context_id = CONTEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Self::new_task_internal(parent, label, context_id)
    }
    #[inline]
    fn new_task_internal(parent: Option<Context>, label: String, context_id: u64) -> Context {
        Context {
            inner: Arc::new(ContextInner {
                parent,
                context_id,
                define_task: Some(Task::new(label)),
                is_tracing: AtomicBool::new(false),
            }),
        }
    }

    /// Resets the current context to a new orphaned task.
    ///
    /// This creates a new context with no parent and sets it as the current
    /// thread-local context. This is useful for starting fresh logging contexts
    /// or for testing.
    ///
    /// # Parameters
    /// * `label` - A human-readable label for the new task.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// Context::reset("fresh_start".to_string());
    /// let context = Context::current();
    /// assert_eq!(context.nesting_level(), 0); // No parent
    /// ```
    #[inline]
    pub fn reset(label: String) {
        let new_context = Context::new_task(None, label);
        new_context.set_current();
    }

    /// Creates a new context that inherits the task from the given parent context.
    ///
    /// This creates a hierarchical relationship without creating a new task.
    /// The child context will inherit the parent's task and tracing state,
    /// but will appear with increased indentation in log output.
    ///
    /// # Parameters
    /// * `context` - The parent context to inherit from.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let parent = Context::new_task(None, "parent_task".to_string());
    /// let child = Context::from_parent(parent.clone());
    ///
    /// // Child inherits the same task ID but has different context ID
    /// assert_eq!(parent.task_id(), child.task_id());
    /// assert_ne!(parent.context_id(), child.context_id());
    /// assert_eq!(child.nesting_level(), parent.nesting_level() + 1);
    /// ```
    pub fn from_parent(context: Context) -> Context {
        let is_tracing = context.inner.is_tracing.load(Ordering::Relaxed);
        Context {
            inner: Arc::new(ContextInner {
                parent: Some(context),
                context_id: CONTEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
                define_task: None,
                is_tracing: AtomicBool::new(is_tracing),
            }),
        }
    }

    /// Returns the task ID associated with this context.
    ///
    /// This is a convenience method that returns the ID of the task
    /// associated with this context (either owned or inherited).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let context = Context::new_task(None, "example".to_string());
    /// let task_id = context.task_id();
    /// println!("Task ID: {}", task_id);
    /// ```
    #[inline]
    pub fn task_id(&self) -> TaskID {
        self.task().task_id
    }

    /// Determines whether this context is currently in tracing mode.
    ///
    /// When tracing is enabled, trace-level logging becomes active and
    /// log output includes trace indicators.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let context = Context::current();
    /// if context.is_tracing() {
    ///     // Trace logging is active
    /// }
    /// ```
    #[inline]
    pub fn is_tracing(&self) -> bool {
        self.inner.is_tracing.load(Ordering::Relaxed)
    }

    /// Returns true if the current thread-local context is in tracing mode.
    ///
    /// This is a convenience method to check the tracing state of the
    /// current context without first retrieving it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// if Context::currently_tracing() {
    ///     // Current context has tracing enabled
    /// }
    /// ```
    #[inline]
    pub fn currently_tracing() -> bool {
        CONTEXT.with(|c| {
            //safety: we don't let anyone get a mutable reference to this
            unsafe { &*c.as_ptr() }
                .inner
                .is_tracing
                .load(Ordering::Relaxed)
        })
    }

    /// Begins tracing for the current context.
    ///
    /// This enables detailed trace logging for the current context and
    /// logs a trace message to mark the beginning of tracing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// // Enable tracing for current context
    /// Context::begin_trace();
    ///
    /// // Now trace macros will be active
    /// logwise::trace_sync!("This trace message will be logged");
    /// ```
    pub fn begin_trace() {
        Context::current()
            .inner
            .is_tracing
            .store(true, Ordering::Relaxed);
        logwise::trace_sync!("Begin trace");
    }

    /// Sets this context as the current thread-local context.
    ///
    /// After calling this method, all logwise macros will use this context
    /// for structured logging output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let new_context = Context::new_task(None, "my_task".to_string());
    /// new_context.set_current();
    ///
    /// // All subsequent logging uses the new context
    /// logwise::info_sync!("This uses my_task context");
    /// ```
    pub fn set_current(self) {
        CONTEXT.replace(self);
    }

    /// Returns the nesting level of this context in the hierarchy.
    ///
    /// This counts the number of parent contexts above this one. Root contexts
    /// (those with no parent) have a nesting level of 0. The nesting level
    /// determines the indentation in log output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let root = Context::new_task(None, "root".to_string());
    /// assert_eq!(root.nesting_level(), 0);
    ///
    /// let child = Context::from_parent(root);
    /// assert_eq!(child.nesting_level(), 1);
    ///
    /// let grandchild = Context::from_parent(child);
    /// assert_eq!(grandchild.nesting_level(), 2);
    /// ```
    pub fn nesting_level(&self) -> usize {
        let mut level = 0;
        let mut current = self;
        while let Some(parent) = &current.inner.parent {
            level += 1;
            current = parent;
        }
        level
    }

    /// Returns the unique identifier of this context.
    ///
    /// Context IDs are used for context management operations like [`Context::pop()`].
    /// Each context has a unique ID, even if they share the same task.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let context = Context::current();
    /// let id = context.context_id();
    /// println!("Context ID: {:?}", id);
    /// ```
    #[inline]
    pub fn context_id(&self) -> ContextID {
        ContextID(self.inner.context_id)
    }

    /// Pops contexts from the stack until reaching the context with the specified ID.
    ///
    /// This method walks up the context hierarchy from the current context,
    /// looking for the context with the given ID. When found, that context's
    /// parent becomes the new current context.
    ///
    /// If the context ID is not found in the current hierarchy, a warning
    /// is logged and no context change occurs.
    ///
    /// # Parameters
    /// * `id` - The context ID to pop back to.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::Context;
    ///
    /// let original = Context::current();
    /// let child = Context::from_parent(original.clone());
    /// let child_id = child.context_id();
    /// child.set_current();
    ///
    /// // Later, pop back to original context
    /// Context::pop(child_id);
    /// assert_eq!(Context::current(), original);
    /// ```
    pub fn pop(id: ContextID) {
        let mut current = Context::current();
        loop {
            if current.context_id() == id {
                let parent = current.inner.parent.clone().expect("No parent context");
                CONTEXT.replace(parent);
                return;
            }
            match current.inner.parent.as_ref() {
                None => {
                    logwise::warn_sync!(
                        "Tried to pop context with ID {id}, but it was not found in the current context chain.",
                        id = id.0
                    );
                    return;
                }
                Some(ctx) => current = ctx.clone(),
            }
        }
    }

    /// Internal implementation detail of the logging system.
    ///
    /// Logs the contextual prefix that includes trace indicator, indentation
    /// based on nesting level, and the task ID. This method is used by the
    /// logwise macros and should not be called directly by user code.
    ///
    /// # Parameters
    /// * `record` - The log record to write the prelude to.
    #[inline]
    pub fn _log_prelude(&self, record: &mut crate::log_record::LogRecord) {
        let prefix = if self.is_tracing() { "T" } else { " " };
        record.log(prefix);
        for _ in 0..self.nesting_level() {
            record.log(" ");
        }
        record.log_owned(format!("{} ", self.task_id()));
    }

    /// Internal method for adding performance interval statistics to the current task.
    ///
    /// This method is used by the `perfwarn!` macro to accumulate timing statistics
    /// that are logged when the task completes. User code should not call this directly.
    ///
    /// # Parameters
    /// * `key` - A static string identifying the type of interval.
    /// * `duration` - The duration to add to the statistics for this key.
    #[inline]
    pub fn _add_task_interval(&self, key: &'static str, duration: crate::sys::Duration) {
        self.task().add_task_interval(key, duration);
    }
}

/// A future wrapper that applies a context during polling.
///
/// This wrapper ensures that the specified context is active during the
/// polling of the wrapped future. This is essential for async executors
/// that may not preserve thread-local state across poll operations.
///
/// When the future is polled, the wrapper:
/// 1. Saves the current context
/// 2. Sets the specified context as current
/// 3. Polls the wrapped future
/// 4. Restores the original context
///
/// This ensures that all logwise macros used within the async code
/// have access to the correct context information.
///
/// # Examples
///
/// ```rust
/// use logwise::context::{Context, ApplyContext};
///
/// let context = Context::new_task(None, "async_task".to_string());
///
/// let future = async {
///     logwise::info_sync!("This will use async_task context");
///     42
/// };
///
/// let wrapped_future = ApplyContext::new(context, future);
/// // Now execute wrapped_future with your async runtime
/// ```
///
/// # Use Cases
///
/// - **Hostile Executors**: Some async executors may poll futures on different
///   threads or in contexts where thread-local storage is not preserved.
/// - **Context Propagation**: Ensuring that spawned async tasks maintain
///   the logging context from their parent.
/// - **Testing**: Applying specific contexts to async test scenarios.
pub struct ApplyContext<F>(Context, F);

impl<F> ApplyContext<F> {
    /// Creates a new `ApplyContext` wrapper.
    ///
    /// # Parameters
    /// * `context` - The context to apply during polling of the future.
    /// * `f` - The future to wrap.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use logwise::context::{Context, ApplyContext};
    ///
    /// let context = Context::current();
    /// let future = async { "hello" };
    /// let wrapped = ApplyContext::new(context, future);
    /// ```
    pub fn new(context: Context, f: F) -> Self {
        Self(context, f)
    }
}

impl<F> Future for ApplyContext<F>
where
    F: Future,
{
    type Output = F::Output;

    /// Polls the wrapped future with the specified context active.
    ///
    /// This implementation saves the current context, applies the wrapped
    /// context, polls the inner future, and then restores the original context.
    /// This ensures that the context is properly maintained even in hostile
    /// async executors.
    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
        let (context, fut) = unsafe {
            let d = self.get_unchecked_mut();
            (d.0.clone(), Pin::new_unchecked(&mut d.1))
        };
        let prior_context = Context::current();
        context.set_current();
        let r = fut.poll(cx);
        prior_context.set_current();
        r
    }
}

#[cfg(test)]
mod tests {
    use super::{Context, Task, TaskID};
    #[cfg(target_arch = "wasm32")]
    use wasm_bindgen_test::*;
    #[cfg(target_arch = "wasm32")]
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn test_new_context() {
        Context::reset("test_new_context".to_string());
        let port_context = Context::current();
        let next_context = Context::from_parent(port_context);
        let next_context_id = next_context.context_id();
        next_context.set_current();

        Context::pop(next_context_id);
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn test_context_equality() {
        Context::reset("test_context_equality".to_string());
        let context1 = Context::current();
        let context2 = context1.clone();
        let context3 = Context::new_task(None, "different_task".to_string());

        // Same Arc pointer should be equal
        assert_eq!(context1, context2);

        // Different Arc pointers should not be equal
        assert_ne!(context1, context3);
        assert_ne!(context2, context3);
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn test_context_hash() {
        use std::collections::HashMap;
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        Context::reset("test_context_hash".to_string());
        let context1 = Context::current();
        let context2 = context1.clone();
        let context3 = Context::new_task(None, "different_task".to_string());

        // Same Arc pointer should have same hash
        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        context1.hash(&mut hasher1);
        context2.hash(&mut hasher2);
        assert_eq!(hasher1.finish(), hasher2.finish());

        // Different Arc pointers should have different hashes (highly likely)
        let mut hasher3 = DefaultHasher::new();
        context3.hash(&mut hasher3);
        assert_ne!(hasher1.finish(), hasher3.finish());

        // Test that Context can be used as HashMap key
        let mut map = HashMap::new();
        map.insert(context1.clone(), "value1");
        map.insert(context3.clone(), "value3");

        assert_eq!(map.get(&context1), Some(&"value1"));
        assert_eq!(map.get(&context2), Some(&"value1")); // same as context1
        assert_eq!(map.get(&context3), Some(&"value3"));
        assert_eq!(map.len(), 2); // only 2 unique contexts
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn test_context_display() {
        Context::reset("root_task".to_string());
        let root_context = Context::current();

        // Root context should have no indentation (nesting level 0)
        let root_display = format!("{}", root_context);
        assert!(root_display.starts_with(&format!("{} (root_task)", root_context.task_id())));
        assert!(!root_display.starts_with("  ")); // no indentation

        // Create a child context
        let child_context = Context::from_parent(root_context.clone());
        child_context.clone().set_current();
        let child_display = format!("{}", child_context);

        // Child should have 1 level of indentation
        assert!(child_display.starts_with("  ")); // 2 spaces for nesting level 1
        assert!(child_display.contains(&format!("{} (root_task)", root_context.task_id())));

        // Create a new task context as child
        let task_context = Context::new_task(Some(child_context.clone()), "child_task".to_string());
        task_context.clone().set_current();
        let task_display = format!("{}", task_context);

        // Task context should have 2 levels of indentation
        assert!(task_display.starts_with("    ")); // 4 spaces for nesting level 2
        assert!(task_display.contains(&format!("{} (child_task)", task_context.task_id())));

        // Create grandchild
        let grandchild_context = Context::from_parent(task_context.clone());
        grandchild_context.clone().set_current();
        let grandchild_display = format!("{}", grandchild_context);

        // Grandchild should have 3 levels of indentation
        assert!(grandchild_display.starts_with("      ")); // 6 spaces for nesting level 3
        assert!(grandchild_display.contains(&format!("{} (child_task)", task_context.task_id())));
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn test_context_as_ref_task() {
        Context::reset("test_as_ref".to_string());
        let context = Context::current();

        // Test that AsRef<Task> works
        let task_ref: &Task = context.as_ref();
        assert_eq!(task_ref.task_id, context.task_id());
        assert_eq!(task_ref.label, "test_as_ref");

        // Test that we can use Context where &Task is expected
        fn takes_task_ref(task: &Task) -> TaskID {
            task.task_id
        }

        // Test explicit AsRef usage
        let id1 = takes_task_ref(context.as_ref());
        assert_eq!(id1, context.task_id());

        // Test with generic function that accepts AsRef<Task>
        fn takes_as_ref_task<T: AsRef<Task>>(item: T) -> TaskID {
            item.as_ref().task_id
        }

        let id2 = takes_as_ref_task(&context);
        let id3 = takes_as_ref_task(context.clone());
        assert_eq!(id1, id2);
        assert_eq!(id2, id3);

        // Test with different context types
        let child_context = Context::from_parent(context.clone());
        let child_task_ref: &Task = child_context.as_ref();

        // Child should have same task as parent (since from_parent preserves task)
        assert_eq!(child_task_ref.task_id, context.task_id());
        assert_eq!(child_task_ref.label, "test_as_ref");

        let new_task_context = Context::new_task(Some(context.clone()), "new_task".to_string());
        let new_task_ref: &Task = new_task_context.as_ref();

        // New task should have different ID and label
        assert_ne!(new_task_ref.task_id, context.task_id());
        assert_eq!(new_task_ref.label, "new_task");
    }
}