Skip to main content

cu29_helpers/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#[cfg(not(feature = "std"))]
3extern crate alloc;
4
5use cu29_clock::RobotClock;
6use cu29_log_runtime::LoggerRuntime;
7use cu29_runtime::curuntime::CopperContext;
8use cu29_traits::{CuError, CuResult, UnifiedLogType, with_cause};
9use cu29_unifiedlog::{UnifiedLogger, UnifiedLoggerBuilder, stream_write};
10use simplelog::TermLogger;
11use std::path::Path;
12use std::sync::{Arc, Mutex};
13
14/// This is a basic setup for a copper application to get you started.
15/// Duplicate and customize as needed when your needs grow.
16///
17/// unifiedlogger_output_base_name: The base name of the log file. The logger will create a set of files based on this name
18///                                  for example if named "toto.copper" it will create toto_0.copper, toto_1.copper etc.
19///
20/// text_log: if true, the log will be printed to the console as a simple log.
21/// It is useful to debug an application in real-time but should be set to false in production
22/// as it is an order of magnitude slower than the default copper structured logging.
23/// It will create a LoggerRuntime that can be used as a robot clock source too.
24///
25/// slab_size: The logger will pre-allocate large files of those sizes. With the name of the given file _0, _1 etc.
26/// clock: if you let it to None it will create a default clock otherwise you can provide your own, for example a simulation clock.
27///        with let (clock , mock) = RobotClock::mock();
28pub fn basic_copper_setup(
29    unifiedlogger_output_base_name: &Path,
30    slab_size: Option<usize>,
31    _text_log: bool,
32    clock: Option<RobotClock>,
33) -> CuResult<CopperContext> {
34    let preallocated_size = slab_size.unwrap_or(1024 * 1024 * 10);
35    let logger = UnifiedLoggerBuilder::new()
36        .write(true)
37        .create(true)
38        .file_base_name(unifiedlogger_output_base_name)
39        .preallocated_size(preallocated_size)
40        .build()
41        .map_err(|e| with_cause("Failed to create unified logger", e))?;
42    let logger = match logger {
43        UnifiedLogger::Write(logger) => logger,
44        UnifiedLogger::Read(_) => {
45            return Err(CuError::from(
46                "UnifiedLoggerBuilder did not create a write-capable logger",
47            ));
48        }
49    };
50    let unified_logger = Arc::new(Mutex::new(logger));
51    let structured_stream = stream_write(
52        unified_logger.clone(),
53        UnifiedLogType::StructuredLogLine,
54        4096 * 10,
55    )?;
56
57    let extra: Option<TermLogger> = None;
58
59    let clock = clock.unwrap_or_default();
60    let structured_logging = LoggerRuntime::init(clock.clone(), structured_stream, extra);
61    Ok(CopperContext {
62        unified_logger: unified_logger.clone(),
63        logger_runtime: structured_logging,
64        clock,
65    })
66}