workflow-log 0.19.0

Log macros & utilities abstracting native & in-browser logging interfaces
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
use cfg_if::cfg_if;
use std::fmt;

cfg_if! {
    if #[cfg(target_arch = "bpf")] {
        pub use workflow_log::levels::{ Level, LevelFilter };
    } else {
        use std::sync::Arc;
        pub use log::{ Level, LevelFilter };
        use downcast::{ downcast_sync, AnySync };
        use crate::hex as hexplay;
        pub use crate::hex::HexViewBuilder;
        pub use termcolor::Buffer;
        //use core::ops::Range;

        /// Builder wrapper around a [`HexViewBuilder`] that accumulates colored
        /// ranges of a hex data dump and renders them via [`ColorHexView::try_print`].
        pub struct ColorHexView<'a>{
            /// The underlying hex view builder that ranges and colors are applied to.
            pub builder: HexViewBuilder<'a>,
            /// Running byte offset marking where the next sequentially-added color range begins.
            pub color_start: usize
        }
        impl<'a> ColorHexView<'a>{
            /// Creates a new view from a [`HexViewBuilder`] and a list of
            /// `(color, length)` pairs applied sequentially from offset zero.
            pub fn new(builder:HexViewBuilder<'a>, colors:Vec<(&'a str, usize)>)->Self{
                Self{
                    builder,
                    color_start:0
                }.add_colors(colors)
            }

            /// Appends `(color, length)` pairs, coloring consecutive byte ranges
            /// starting at the current offset and advancing it by each length.
            pub fn add_colors(mut self, colors:Vec<(&'a str, usize)>)->Self{
                let mut builder = self.builder;
                for (color, len) in colors{
                    let end = self.color_start+len;
                    let range = self.color_start..end;
                    self.color_start = end;
                    builder = builder.add_color(color, range);
                }
                self.builder = builder;
                self
            }

            /// Applies `(color, range)` pairs, coloring each explicitly specified
            /// byte range of the hex dump.
            pub fn add_colors_with_range(mut self, colors:Vec<(&'a str, std::ops::Range<usize>)>)->Self{
                let mut builder = self.builder;
                for (color, range) in colors{
                    builder = builder.add_color(color, range);
                }
                self.builder = builder;
                self
            }

            /// Renders the colored hex view and emits it via [`log_trace`],
            /// returning an error string if formatting or UTF-8 conversion fails.
            pub fn try_print(self)->std::result::Result<(), String>{
                let mut buf = Buffer::ansi();
                match self.builder.finish().fmt(&mut buf){
                    Ok(()) => {
                        match String::from_utf8(buf.as_slice().to_vec()){
                            Ok(str)=>{
                                log_trace!("{}", str);
                            }
                            Err(_)=>{
                                return Err("Unable to convert HexView to string".to_string());
                            }
                        }
                    },
                    Err(_) => {
                        return Err("Unable to format HexView".to_string());
                    }
                }
                Ok(())
            }
        }

        /// A log sink trait that can be installed into the log subsystem using the [`pipe`]
        /// function and will receive all log messages.
        pub trait Sink : AnySync {
            /// Receives a single log message; returns `true` to allow the message
            /// to continue to the default console output, or `false` to consume it.
            fn write(&self, target: Option<&str>, level : Level, args : &fmt::Arguments<'_>) -> bool;
        }

        #[allow(unused)]
        struct SinkHandler {
            // #[allow(dead_code)]
            sink : Arc<dyn Sink>, // + Send + Sync + 'static>,
        }

        downcast_sync!(dyn Sink);
    }
}

cfg_if! {
    if #[cfg(target_arch = "bpf")] {
        #[inline(always)]
        pub fn log_level_enabled(_level: Level) -> bool {
            true
        }
    } else if #[cfg(target_arch = "wasm32")] {
        use wasm_bindgen::prelude::*;

        static mut LEVEL_FILTER : LevelFilter = LevelFilter::Info;
        #[inline(always)]
        pub fn log_level_enabled(level: Level) -> bool {
            unsafe { LEVEL_FILTER >= level }
        }
        pub fn set_log_level(level: LevelFilter) {
            unsafe { LEVEL_FILTER = level };
        }

        #[wasm_bindgen]
        extern "C" {
            #[wasm_bindgen(typescript_type = r###""off" | "error" | "warn" | "info" | "debug" | "trace""###)]
            #[derive(Debug)]
            pub type LogLevelT;
        }

        #[doc="Set the logger log level using a string representation."]
        #[doc="Available variants are: 'off', 'error', 'warn', 'info', 'debug', 'trace'"]
        #[doc="@category General"]
        #[wasm_bindgen(js_name = "setLogLevel")]
        // pub fn set_log_level_str(level: &str) {
        pub fn set_log_level_wasm(level: LogLevelT) {
            if let Some(level) = level.as_string() {
                let level = match level.as_str() {
                    "off" => LevelFilter::Off,
                    "error" => LevelFilter::Error,
                    "warn" => LevelFilter::Warn,
                    "info" => LevelFilter::Info,
                    "debug" => LevelFilter::Debug,
                    "trace" => LevelFilter::Trace,
                    _ => panic!("Invalid log level: {level}"),
                };
                set_log_level(level);
            } else {
                panic!("log level must be a string, received: {level:?}");
            }
        }

        cfg_if! {
            if #[cfg(feature = "sink")] {
                use std::sync::Mutex;
                static SINK : Mutex<Option<SinkHandler>> = Mutex::new(None);
                // pub fn pipe(sink : Arc<dyn Sink + Send + Sync + 'static>) {
                pub fn pipe(sink : Option<Arc<dyn Sink>>) {
                    match sink {
                        Some(sink) => { *SINK.lock().unwrap() = Some(SinkHandler { sink }); },
                        None => { *SINK.lock().unwrap() = None; }
                    }
                }
                #[inline(always)]
                fn to_sink(target: Option<&str>, level : Level, args : &fmt::Arguments<'_>) -> bool {
                    match SINK.lock().unwrap().as_ref() {
                        Some(handler) => {
                            handler.sink.write(target, level, args)
                        },
                        None => { false }
                    }
                }
            }
        }

    } else {
        use std::sync::Mutex;

        lazy_static::lazy_static! {
            static ref LEVEL_FILTER : Mutex<LevelFilter> = Mutex::new(LevelFilter::Info);
        }
        #[inline(always)]
        /// Returns true if the current log level is below the
        /// currently set [`LevelFilter`]
        pub fn log_level_enabled(level: Level) -> bool {
            *LEVEL_FILTER.lock().unwrap() >= level
        }
        /// Enable filtering of log messages using the [`LevelFilter`]
        pub fn set_log_level(level: LevelFilter) {
            *LEVEL_FILTER.lock().unwrap() = level;
        }
        cfg_if! {
            if #[cfg(feature = "sink")] {
                lazy_static::lazy_static! {
                    static ref SINK : Mutex<Option<SinkHandler>> = Mutex::new(None);
                }
                // pub fn pipe(sink : Option<Arc<dyn Sink + Send + Sync + 'static>>) {
                /// Receives an Option with an `Arc`ed [`Sink`] trait reference
                /// and installs it as a log sink / receiver.
                /// The sink can be later disabled by invoking `pipe(None)`
                pub fn pipe(sink : Option<Arc<dyn Sink>>) {
                    match sink {
                        Some(sink) => { *SINK.lock().unwrap() = Some(SinkHandler { sink }); },
                        None => { *SINK.lock().unwrap() = None; }
                    }

                }
                #[inline(always)]
                fn to_sink(target : Option<&str>, level : Level, args : &fmt::Arguments<'_>) -> bool {
                    match SINK.lock().unwrap().as_ref() {
                        Some(handler) => {
                            handler.sink.write(target, level, args)
                        },
                        None => { false }
                    }
                }
            }
        }

        #[cfg(feature = "external-logger")]
        mod workflow_logger {
            use log::{ Level, LevelFilter, Record, Metadata, SetLoggerError };

            pub struct WorkflowLogger;

            impl log::Log for WorkflowLogger {
                fn enabled(&self, metadata: &Metadata) -> bool {
                    super::log_level_enabled(metadata.level())
                }

                fn log(&self, record: &Record) {
                    if self.enabled(record.metadata()) {
                        match record.metadata().level() {
                            Level::Error => { super::error_impl(record.args()); },
                            Level::Warn => { super::warn_impl(record.args()); },
                            Level::Info => { super::info_impl(record.args()); },
                            Level::Debug => { super::debug_impl(record.args()); },
                            Level::Trace => { super::trace_impl(record.args()); },
                        }
                    }
                }

                fn flush(&self) {}
            }

            static LOGGER: WorkflowLogger = WorkflowLogger;

            pub fn init() -> Result<(), SetLoggerError> {
                log::set_logger(&LOGGER)
                    .map(|()| log::set_max_level(LevelFilter::Trace))
            }
        }

        #[cfg(feature = "external-logger")]
        pub fn init() -> Result<(), log::SetLoggerError> {
            workflow_logger::init()
        }

    }
}

#[cfg(target_arch = "wasm32")]
pub mod wasm_log {
    use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = console)]
        pub fn log(s: &str);
        #[wasm_bindgen(js_namespace = console)]
        pub fn warn(s: &str);
        #[wasm_bindgen(js_namespace = console)]
        pub fn error(s: &str);
    }
}

/// Backing implementation functions invoked by the `log_*!` macros to route
/// messages to the sink, browser console, Solana log, or standard output.
pub mod impls {
    use super::*;

    #[inline(always)]
    #[allow(unused_variables)]
    /// Emits a message at [`Level::Error`], honoring the current level filter and sink.
    pub fn error_impl(target: Option<&str>, args: &fmt::Arguments<'_>) {
        if log_level_enabled(Level::Error) {
            #[cfg(all(not(target_arch = "bpf"), feature = "sink"))]
            {
                if to_sink(target, Level::Error, args) {
                    return;
                }
            }
            cfg_if! {
                if #[cfg(target_arch = "wasm32")] {
                    workflow_log::wasm_log::error(&args.to_string());
                } else if #[cfg(target_arch = "bpf")] {
                    solana_program::log::sol_log(&args.to_string());
                } else {
                    println!("{args}");
                }
            }
        }
    }

    #[inline(always)]
    #[allow(unused_variables)]
    /// Emits a message at [`Level::Warn`], honoring the current level filter and sink.
    pub fn warn_impl(target: Option<&str>, args: &fmt::Arguments<'_>) {
        if log_level_enabled(Level::Warn) {
            #[cfg(all(not(target_arch = "bpf"), feature = "sink"))]
            {
                if to_sink(target, Level::Warn, args) {
                    return;
                }
            }
            cfg_if! {
                if #[cfg(target_arch = "wasm32")] {
                    workflow_log::wasm_log::warn(&args.to_string());
                } else if #[cfg(target_arch = "bpf")] {
                    solana_program::log::sol_log(&args.to_string());
                } else {
                    println!("{args}");
                }
            }
        }
    }

    #[inline(always)]
    #[allow(unused_variables)]
    /// Emits a message at [`Level::Info`], honoring the current level filter and sink.
    pub fn info_impl(target: Option<&str>, args: &fmt::Arguments<'_>) {
        if log_level_enabled(Level::Info) {
            #[cfg(all(not(target_arch = "bpf"), feature = "sink"))]
            {
                if to_sink(target, Level::Info, args) {
                    return;
                }
            }
            cfg_if! {
                if #[cfg(target_arch = "wasm32")] {
                    workflow_log::wasm_log::log(&args.to_string());
                } else if #[cfg(target_arch = "bpf")] {
                    solana_program::log::sol_log(&args.to_string());
                } else {
                    println!("{args}");
                }
            }
        }
    }

    #[inline(always)]
    #[allow(unused_variables)]
    /// Emits a message at [`Level::Debug`], honoring the current level filter and sink.
    pub fn debug_impl(target: Option<&str>, args: &fmt::Arguments<'_>) {
        if log_level_enabled(Level::Debug) {
            #[cfg(all(not(target_arch = "bpf"), feature = "sink"))]
            {
                if to_sink(target, Level::Debug, args) {
                    return;
                }
            }
            cfg_if! {
                if #[cfg(target_arch = "wasm32")] {
                    workflow_log::wasm_log::log(&args.to_string());
                } else if #[cfg(target_arch = "bpf")] {
                    solana_program::log::sol_log(&args.to_string());
                } else {
                    println!("{args}");
                }
            }
        }
    }

    #[inline(always)]
    #[allow(unused_variables)]
    /// Emits a message at [`Level::Trace`], honoring the current level filter and sink.
    pub fn trace_impl(target: Option<&str>, args: &fmt::Arguments<'_>) {
        if log_level_enabled(Level::Trace) {
            #[cfg(all(not(target_arch = "bpf"), feature = "sink"))]
            {
                if to_sink(target, Level::Trace, args) {
                    return;
                }
            }
            cfg_if! {
                if #[cfg(target_arch = "wasm32")] {
                    workflow_log::wasm_log::log(&args.to_string());
                } else if #[cfg(target_arch = "bpf")] {
                    solana_program::log::sol_log(&args.to_string());
                } else {
                    println!("{args}");
                }
            }
        }
    }
}

/// Format and log message with [`Level::Error`]
#[macro_export]
macro_rules! log_error {
    (target: $target:expr_2021, $($arg:tt)+) => (
        workflow_log::impls::error_impl(Some($target),&format_args!($($t)*))
    );

    ($($t:tt)*) => (
        workflow_log::impls::error_impl(None,&format_args!($($t)*))
    )
}

/// Format and log message with [`Level::Warn`]
#[macro_export]
macro_rules! log_warn {
    (target: $target:expr_2021, $($arg:tt)+) => (
        workflow_log::impls::warn_impl(Some($target),&format_args!($($t)*))
    );

    ($($t:tt)*) => (
        workflow_log::impls::warn_impl(None,&format_args!($($t)*))
    )
}

/// Format and log message with [`Level::Info`]
#[macro_export]
macro_rules! log_info {
    (target: $target:expr_2021, $($arg:tt)+) => (
        workflow_log::impls::info_impl(Some($target),&format_args!($($t)*))
    );

    ($($t:tt)*) => (
        workflow_log::impls::info_impl(None,&format_args!($($t)*))
    )
}

/// Format and log message with [`Level::Debug`]
#[macro_export]
macro_rules! log_debug {
    (target: $target:expr_2021, $($arg:tt)+) => (
        workflow_log::impls::debug_impl(Some($target),&format_args!($($t)*))
    );

    ($($t:tt)*) => (
        workflow_log::impls::debug_impl(None,&format_args!($($t)*))
    )
}

/// Format and log message with [`Level::Trace`]
#[macro_export]
macro_rules! log_trace {
    (target: $target:expr_2021, $($arg:tt)+) => (
        workflow_log::impls::trace_impl(Some($target),&format_args!($($t)*))
    );

    ($($t:tt)*) => (
        workflow_log::impls::trace_impl(None,&format_args!($($t)*))
    )
}

pub use log_debug;
pub use log_error;
pub use log_info;
pub use log_trace;
pub use log_warn;

/// Prints (using [`log_trace`]) a data slice
/// formatted as a hex data dump.
#[cfg(not(target_arch = "bpf"))]
pub fn trace_hex(data: &[u8]) {
    let hex = format_hex(data);
    log_trace!("{}", hex);
}

/// Returns a string formatted as a hex data dump
/// of the supplied slice argument.
#[cfg(not(target_arch = "bpf"))]
pub fn format_hex(data: &[u8]) -> String {
    let view = hexplay::HexViewBuilder::new(data)
        .address_offset(0)
        .row_width(16)
        .finish();

    format!("{view}")
}

/// Formats a hex data dump to contain color ranges
#[cfg(not(target_arch = "bpf"))]
pub fn format_hex_with_colors<'a>(
    data: &'a [u8],
    colors: Vec<(&'a str, usize)>,
) -> ColorHexView<'a> {
    let view_builder = hexplay::HexViewBuilder::new(data)
        .address_offset(0)
        .row_width(16);

    ColorHexView::new(view_builder, colors)
}
#[cfg(not(target_arch = "bpf"))]
/// Trait helpers for emitting a type's binary data as a colorized hex dump.
pub mod color_log {
    use super::*;
    type Index = usize;
    type Length = usize;
    type Color<'a> = &'a str;
    type Result<T> = std::result::Result<T, String>;
    /// Implemented by types that can render themselves as a colorized hex dump
    /// via [`log_trace`].
    pub trait ColoLogTrace {
        /// Returns the raw bytes to be rendered as a hex dump.
        fn log_data(&self) -> Vec<u8>;
        /// Returns optional `(index, length, color)` tuples describing colored
        /// byte ranges; defaults to `None` for an uncolored dump.
        fn log_index_length_color(&self) -> Option<Vec<(Index, Length, Color<'_>)>> {
            None
        }

        /// Renders the data (with any specified colors) as a hex dump and emits
        /// it via [`log_trace`], falling back to an uncolored dump on failure.
        fn log_trace(&self) -> Result<bool> {
            let data_vec = self.log_data();
            let mut view = format_hex_with_colors(&data_vec, vec![]);
            if let Some(index_length_color) = self.log_index_length_color() {
                let mut colors = Vec::new();
                for (index, length, color) in index_length_color {
                    colors.push((color, index..index + length));
                }
                view = view.add_colors_with_range(colors);
            }

            if view.try_print().is_err() {
                trace_hex(&data_vec);
                return Ok(false);
            }
            Ok(true)
        }
    }
}

#[cfg(not(target_arch = "bpf"))]
pub use color_log::*;