open_net/api/log/logger.rs
1use super::{LogLevel, LogListener, LogSubscriptionOptions, LogType, SharedLogListener};
2use crate::common::log::logger::{self, SubscriptionState};
3use std::io;
4use std::sync::Arc;
5
6const DEFAULT_QUEUE_CAPACITY: usize = 256;
7
8/// Cumulative capacity-related drops for one subscription.
9///
10/// Checks are ordered: single-record size, queued-byte budget, then queue slots.
11/// Each rejected record contributes to exactly one counter. Filtering, closure,
12/// and suppressed overflow reports are not counted. Concurrent updates mean the
13/// fields need not represent one atomic instant.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct LogDropStats {
17 /// Records discarded because no queue slot was available.
18 pub queue_full: u64,
19 /// Records discarded because the queued/reserved byte budget was exhausted.
20 pub byte_budget: u64,
21 /// Records exceeding the configured single-record byte limit.
22 pub oversized: u64,
23}
24
25/// Owns a single filtered log subscription. Dropping it stops accepting records,
26/// wakes an idle callback thread without waiting for an already-running callback.
27/// Pending records are discarded when the worker exits; a blocked callback can
28/// retain its queue until it returns. This handle may be shared or moved across threads.
29///
30/// Callbacks run sequentially on a dedicated thread. They may query the SDK,
31/// replace/unsubscribe listeners or panic without blocking network workers. Logs
32/// synchronously produced on the callback thread are suppressed to prevent loops.
33/// Work explicitly spawned by a callback must avoid creating its own log loop.
34#[must_use = "keep the subscription alive to continue receiving logs"]
35pub struct LogSubscription {
36 pub(crate) id: u64,
37 pub(crate) state: Arc<SubscriptionState>,
38}
39
40impl LogSubscription {
41 /// Total records discarded because this subscription's queue was full.
42 pub fn dropped_count(&self) -> u64 {
43 self.state.dropped_count()
44 }
45
46 /// Reads cumulative drops. `dropped_count()` remains equal to `queue_full`;
47 /// it does not include byte-budget or single-record-size rejections.
48 pub fn drop_stats(&self) -> LogDropStats {
49 self.state.drop_stats()
50 }
51}
52
53impl Drop for LogSubscription {
54 fn drop(&mut self) {
55 logger::unregister(self.id, &self.state);
56 }
57}
58
59/// Callback-only logging. The library does not print or persist log records.
60pub struct OpenNetLogger;
61
62impl OpenNetLogger {
63 /// Registers an independent subscription with a queue of 256 records.
64 ///
65 /// Only explicitly listed origins are accepted, including for overflow reports.
66 /// An empty type list is invalid. The returned handle must remain alive.
67 /// Registration can fail if the callback thread cannot be created.
68 pub fn register_log_listener(
69 listener: LogListener,
70 log_types: &[LogType],
71 ) -> io::Result<LogSubscription> {
72 Self::register_log_listener_with_capacity(listener, log_types, DEFAULT_QUEUE_CAPACITY)
73 }
74
75 /// Registers a subscription with a bounded number of queued records.
76 ///
77 /// Producers never wait for queue capacity. Overflow increments
78 /// [`LogSubscription::dropped_count`] and is reported after the consumer resumes
79 /// as a synthetic `log_subscription_overflow` record using the first listed
80 /// origin.
81 ///
82 /// Capacity must be in `1..=16_384`. Zero, larger capacities and an empty
83 /// type list return [`io::ErrorKind::InvalidInput`] before allocating the
84 /// queue or starting the callback thread. The limit counts queued records,
85 /// not their payload bytes or the total memory used by all subscriptions.
86 /// Registration can also fail if the callback thread cannot be created.
87 pub fn register_log_listener_with_capacity(
88 listener: LogListener,
89 log_types: &[LogType],
90 capacity: usize,
91 ) -> io::Result<LogSubscription> {
92 logger::register_log_listener_with_capacity(listener, log_types, capacity)
93 }
94
95 /// Registers a subscription sharing immutable records with other listeners.
96 ///
97 /// Only configured origins and levels are delivered. Exported log macros skip
98 /// content parameter evaluation when no subscription needs the origin/level;
99 /// another listener (including a legacy listener accepting every level) may
100 /// still require construction. Concurrent subscription changes can occur
101 /// after this check. Legacy listeners receive owned records at delivery time
102 /// and can still require a deep copy.
103 ///
104 /// Producers never wait for queue space. Records exceeding a configured limit
105 /// are dropped whole and counted by [`LogSubscription::drop_stats`]. A Debug
106 /// `log_subscription_overflow` report can be delivered after a callback
107 /// returns, using the first configured origin. It bypasses the queue but
108 /// obeys the subscription's level and single-record limit. A suppressed report
109 /// does not create another drop; counters remain available independently.
110 ///
111 /// Returns [`io::ErrorKind::InvalidInput`] before allocating a queue or starting
112 /// a worker for empty origins, a capacity outside `1..=16_384`, zero byte
113 /// limits, or a single-record limit greater than the queued-byte limit.
114 /// Registration can also fail if the callback thread cannot be created.
115 ///
116 /// ```
117 /// use open_net::{LogLevel, LogSubscriptionOptions, LogType, OpenNetLogger};
118 /// let subscription = OpenNetLogger::register_shared_log_listener(
119 /// Box::new(|record| eprintln!("{}: {}", record.tag, record.content)),
120 /// LogSubscriptionOptions::new(&[LogType::Engine, LogType::HTTP])
121 /// .with_max_level(LogLevel::Warn),
122 /// )?;
123 /// // Keep the handle alive while logging is needed.
124 /// let oversized = subscription.drop_stats().oversized;
125 /// # Ok::<(), std::io::Error>(())
126 /// ```
127 pub fn register_shared_log_listener(
128 listener: SharedLogListener,
129 options: LogSubscriptionOptions,
130 ) -> io::Result<LogSubscription> {
131 logger::register_shared_log_listener(listener, options)
132 }
133
134 /// Clears all global subscriptions without waiting for callbacks in progress.
135 pub fn clear_global_log_listener() {
136 logger::clear_global_log_listener();
137 }
138
139 /// Used by macros to avoid evaluating arguments for disabled origins.
140 #[doc(hidden)]
141 pub fn is_enabled(log_type: LogType) -> bool {
142 logger::is_enabled(log_type)
143 }
144
145 /// Used by exported macros to check joint origin and severity interest.
146 #[doc(hidden)]
147 pub fn is_enabled_for(log_type: LogType, level: LogLevel) -> bool {
148 logger::is_enabled_for(log_type, level)
149 }
150}