File: test_multi_threaded_stderr.rs

package info (click to toggle)
rust-flexi-logger 0.29.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,084 kB
  • sloc: makefile: 2
file content (70 lines) | stat: -rw-r--r-- 2,321 bytes parent folder | download
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
mod test_utils;

use flexi_logger::{Logger, WriteMode};
use log::*;
use std::thread::{self, JoinHandle};

const NO_OF_THREADS: usize = 5;
const NO_OF_LOGLINES_PER_THREAD: usize = 5_000;

#[test]
fn multi_threaded() {
    test_utils::wait_for_start_of_second();
    let _logger = Logger::try_with_str("debug")
        .unwrap()
        .log_to_stderr()
        .write_mode(WriteMode::BufferAndFlushWith(
            1024,
            std::time::Duration::from_millis(600),
        ))
        .start()
        .unwrap_or_else(|e| panic!("Logger initialization failed with {e}"));
    info!("create a huge number of log lines with a considerable number of threads");
    for i in 0..50 {
        std::thread::sleep(std::time::Duration::from_millis(100));
        info!("********** check delay of this log line ({}) **********", i);
    }
    let _stopwatch = test_utils::Stopwatch::default();

    let worker_handles = start_worker_threads(NO_OF_THREADS);

    wait_for_workers_to_close(worker_handles);
}

// Starts given number of worker threads and lets each execute `do_work`
fn start_worker_threads(no_of_workers: usize) -> Vec<JoinHandle<u8>> {
    let mut worker_handles: Vec<JoinHandle<u8>> = Vec::with_capacity(no_of_workers);
    trace!("Starting {} worker threads", no_of_workers);
    for thread_number in 0..no_of_workers {
        trace!("Starting thread {}", thread_number);
        worker_handles.push(
            thread::Builder::new()
                .name(thread_number.to_string())
                .spawn(move || {
                    do_work(thread_number);
                    0
                })
                .unwrap(),
        );
    }
    trace!("All {} worker threads started.", worker_handles.len());
    worker_handles
}

fn do_work(thread_number: usize) {
    trace!("({})     Thread started working", thread_number);
    trace!("ERROR_IF_PRINTED");
    for idx in 0..NO_OF_LOGLINES_PER_THREAD {
        debug!("({})  writing out line number {}", thread_number, idx);
    }
    trace!("MUST_BE_PRINTED");
}

fn wait_for_workers_to_close(worker_handles: Vec<JoinHandle<u8>>) {
    for worker_handle in worker_handles {
        worker_handle
            .join()
            .unwrap_or_else(|e| panic!("Joining worker thread failed: {e:?}"));
    }
    trace!("All worker threads joined.");
}