You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.2 KiB

  1. use crate::error::Error;
  2. use env_logger::Builder;
  3. use log::LevelFilter;
  4. use syslog::Facility;
  5. pub const DEFAULT_LOG_SYSTEM: LogSystem = LogSystem::SysLog;
  6. pub const DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Warn;
  7. #[derive(Debug, PartialEq, Eq)]
  8. pub enum LogSystem {
  9. SysLog,
  10. StdErr,
  11. }
  12. fn get_loglevel(log_level: Option<&str>) -> Result<LevelFilter, Error> {
  13. let level = match log_level {
  14. Some(v) => match v {
  15. "error" => LevelFilter::Error,
  16. "warn" => LevelFilter::Warn,
  17. "info" => LevelFilter::Info,
  18. "debug" => LevelFilter::Debug,
  19. "trace" => LevelFilter::Trace,
  20. _ => {
  21. return Err(format!("{}: invalid log level", v).into());
  22. }
  23. },
  24. None => DEFAULT_LOG_LEVEL,
  25. };
  26. Ok(level)
  27. }
  28. fn set_log_syslog(log_level: LevelFilter) -> Result<(), Error> {
  29. syslog::init(
  30. Facility::LOG_DAEMON,
  31. log_level,
  32. Some(env!("CARGO_PKG_NAME")),
  33. )?;
  34. Ok(())
  35. }
  36. fn set_log_stderr(log_level: LevelFilter) -> Result<(), Error> {
  37. let mut builder = Builder::from_env("ACMED_LOG_LEVEL");
  38. builder.filter_level(log_level);
  39. builder.init();
  40. Ok(())
  41. }
  42. pub fn set_log_system(
  43. log_level: Option<&str>,
  44. has_syslog: bool,
  45. has_stderr: bool,
  46. ) -> Result<(LogSystem, LevelFilter), Error> {
  47. let log_level = get_loglevel(log_level)?;
  48. let logtype = if has_syslog {
  49. LogSystem::SysLog
  50. } else if has_stderr {
  51. LogSystem::StdErr
  52. } else {
  53. DEFAULT_LOG_SYSTEM
  54. };
  55. match logtype {
  56. LogSystem::SysLog => set_log_syslog(log_level)?,
  57. LogSystem::StdErr => set_log_stderr(log_level)?,
  58. };
  59. Ok((logtype, log_level))
  60. }
  61. #[cfg(test)]
  62. mod tests {
  63. use super::{set_log_system, DEFAULT_LOG_LEVEL, DEFAULT_LOG_SYSTEM};
  64. #[test]
  65. fn test_invalid_level() {
  66. let ret = set_log_system(Some("invalid"), false, false);
  67. assert!(ret.is_err());
  68. }
  69. #[test]
  70. fn test_default_values() {
  71. let ret = set_log_system(None, false, false);
  72. assert!(ret.is_ok());
  73. let (logtype, log_level) = ret.unwrap();
  74. assert_eq!(logtype, DEFAULT_LOG_SYSTEM);
  75. assert_eq!(log_level, DEFAULT_LOG_LEVEL);
  76. }
  77. }