prettylogger/json.rs
1use crate::{Logger, Error};
2use std::{
3 fs::{File, read_to_string},
4 io::Write,
5};
6
7impl Logger {
8 /// Creates a `Logger` instance from a JSON template as string.
9 ///
10 /// # Examples
11 ///
12 /// Deserializing `Logger` from a JSON string:
13 /// ```
14 /// # use prettylogger::Logger;
15 /// let pretty_json = serde_json::to_string_pretty(&Logger::default())
16 /// .expect("Failed to serialize logger!");
17 ///
18 /// let mut logger = Logger::from_template_str(&pretty_json)
19 /// .expect("Failed to deserialize logger!");
20 /// # let raw_json = serde_json::to_string(&Logger::default())
21 /// # .expect("Failed to serialize logger!");
22 /// # assert_eq!(Logger::default(), Logger::from_template_str(&pretty_json)
23 /// # .expect("Failed to deserialize logger!"));
24 /// # assert_eq!(Logger::default(), Logger::from_template_str(&raw_json)
25 /// # .expect("Failed to deserialize logger!"));
26 /// ```
27 pub fn from_template_str(template: &str) -> Result<Logger, Error> {
28 let result: Result<Logger, serde_json::Error>
29 = serde_json::from_str(template);
30 match result {
31 Ok(logger) => {
32 return Ok(logger);
33 },
34 Err(e) => Err(Error::new(&e.to_string()))
35 }
36 }
37
38 /// Creates a `Logger` instance from a template file.
39 ///
40 /// # Examples
41 ///
42 /// Deserializing `Logger` from a JSON file:
43 /// ```
44 /// # use prettylogger::Logger;
45 /// # let mut path = std::env::temp_dir();
46 /// # path.push("libprettylogger-tests/from-template.json");
47 /// # let path = &path.to_str().unwrap().to_string();
48 /// # Logger::default().save_template(path);
49 /// let mut logger = Logger::from_template(path)
50 /// .expect("Failed to deserialize logger!");
51 /// # assert_eq!(Logger::default(), logger);
52 /// ```
53 pub fn from_template(path: &str) -> Result<Logger, Error> {
54 match read_to_string(path) {
55 Ok(contents) => {
56 Logger::from_template_str(&contents)
57 },
58 Err(e) => Err(Error::new(&e.to_string()))
59 }
60 }
61
62 /// Saves a `Logger` instance to template file.
63 ///
64 /// # Examples
65 ///
66 /// Serializing a `Logger` instance to a file:
67 /// ```
68 /// # use prettylogger::Logger;
69 /// # let mut path = std::env::temp_dir();
70 /// # path.push("libprettylogger-tests/from-template.json");
71 /// # let path = &path.to_str().unwrap().to_string();
72 /// let mut logger = Logger::default();
73 /// logger.save_template(path);
74 /// # assert_eq!(Logger::from_template(path)
75 /// .expect("Failed to deserialize logger!"), Logger::default());
76 /// ```
77 pub fn save_template(&self, path: &str) -> Result<(), Error> {
78 let json = serde_json::to_string_pretty(self);
79 match json {
80 Ok(json) => {
81 match File::create(path) {
82 Ok(mut file) => {
83 match file.write_all(json.as_bytes()) {
84 Ok(_) => Ok(()),
85 Err(e) => {
86 Err(Error::new(&e.to_string()))
87 }
88 }
89 },
90 Err(e) => Err(Error::new(&e.to_string()))
91 }
92 },
93 Err(e) => Err(Error::new(&e.to_string()))
94 }
95 }
96}