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
use crate::*;


use std::sync::{Arc, Mutex};

use chrono::prelude::*;


type LogContext = Arc<Mutex<Vec<String>>>;


/// Sessions are a way to group log messages together. They are useful for tracking the flow of a
/// program. They can be nested, and when a session is dropped, it will dump all of its messages to
/// the file at once. Despite the file being written to at once, the messages are still written in
/// the traditional order on the terminal. It can also be used as a simple profiling tool, as it
/// will track the starting time of the session and the elapsed time when it is dropped.
///
/// # Example
///
/// ```no_run
/// use session_log::{Logger, Loggable};
///
/// fn main() {
///   let logger = Logger::new("main");
///
///   foo(logger.session("foo"), 10);
///   bar(logger.session("bar"), 10);
/// }
///
/// fn foo(logger: impl Loggable, n: usize) {
///   for i in 0..n {
///     logger.info(&format!("message-{}", i));
///   }
/// }
///
/// fn bar(logger: impl Loggable, n: usize) {
///   for i in 0..n {
///     logger.warning(&format!("message-{}", i));
///   }
/// }
/// ```
pub struct Session {
  died: bool,
  name: String,
  root: String,
  msgs: LogContext,
  sire: Option<LogContext>,
  time: DateTime<Local>,
  file: &'static str,
  line: u32,
}


impl Session {
  pub(crate) fn new(name: &str, logger: &str, file: &'static str, line: u32) -> Session {
    let msgs = Arc::new(Mutex::new(Vec::new()));
    let sire = None;
    let time = Local::now();

    let ses = Session {
      died: false,
      name: name.to_string(),
      root: logger.to_string(),
      time,
      msgs,
      sire,
      file,
      line,
    };

    ses.log(Context::SessionStart {
      time,
      file,
      line,
      logger,
      session: name,
    });

    ses
  }

  /// Create a nested session under the current session.
  #[track_caller]
  pub fn session(&self, name: &str) -> Result<Session, SessionErrorKind> {
    if self.died { return Err(SessionErrorKind::SessionDied); }

    let msgs = Arc::new(Mutex::new(Vec::new()));
    let sire = Some(self.msgs.clone());
    let time = Local::now();

    let loc  = std::panic::Location::caller();
    let file = loc.file();
    let line = loc.line();

    let ses = Session {
      died: false,
      name: name.to_string(),
      root: self.root.clone(),
      time,
      msgs,
      sire,
      file,
      line,
    };

    ses.log(Context::SessionStart {
      time,
      file,
      line,
      logger : &self.root,
      session: &self.name,
    });

    Ok(ses)
  }

  pub(self) fn dump(&mut self) {
    if self.died { return; }
    self.died = true;

    let mut rslt = Vec::new();
    let     time = Local::now();
    let     msgs = self.msgs.lock().unwrap();

    rslt.reserve(7 + msgs.len());

    println!("{} {:#} {}:{} - Session ended",
      time.to_rfc3339_opts(SecondsFormat::Micros, true),
      Level::Info,
      self.root,
      self.name);

    rslt.push(format!("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
    rslt.push(format!("┃ Session: {}", self.name));
    rslt.push(format!("┃ Elapsed: {}us", (time - self.time).num_microseconds().unwrap()));
    rslt.push(format!("┃"));

    for msg in msgs.iter() {
      for line in msg.lines() {
        let is_border = line.starts_with("┏") || line.starts_with("┗");
        let is_nested = line.starts_with("┃") || is_border;

        let space = if is_nested { ""                    } else { " "  };
        let line  = if is_border { &line[..line.len()-3] } else { line };

        rslt.push(format!("┃{space}{line}"));
      }
    }

    rslt.push(format!("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));

    if let Some(sire) = &self.sire {
      sire.lock().unwrap().append(&mut rslt);
      return;
    }

    Logger::new(&self.root).write_line(&rslt.join("\n"));
  }
}


impl Loggable for Session {
  fn log(&self, ctx: crate::Context) {
    if self.died { return; }

    let logger = Logger::new(&self.root);
    if let Some(level) = ctx.get_level() {
      if level < &logger.get_level() { return; }
    }

    let message = (logger.get_processor())(&ctx);
    self.msgs.lock().unwrap().push(message);
  }

  fn get_logger(&self) -> &str {
    &self.root
  }

  fn get_session(&self) -> Option<&str> {
    Some(&self.name)
  }
}


impl Drop for Session {
  fn drop(&mut self) {
    self.log(Context::SessionEnd {
      time   : Local::now(),
      file   : self.file,
      line   : self.line,
      logger : &self.root,
      session: &self.name,
    });

    self.dump();
  }
}