somesingsomsing
somesingsomsing

Reputation: 3350

log4rs error Log4rs(Os { code: 2, kind: NotFound, message: "No such file or directory" })

I'm trying to implement log4rs by following the docs. My goal is to put the result of info!("INFO") into the file requests.log, but I get an error:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Log4rs(Os { code: 2, kind: NotFound, message: "No such file or directory" })', libcore/result.rs:945:5

I have the following files in the src folder:

- main.rs
- log4rs.yml
- requests.log

main.rs:

#[macro_use]
extern crate log;
extern crate log4rs;

fn main() {
    println!("Hello, world!");
    log4rs::init_file("log4rs.yml", Default::default()).unwrap();
    info!("INFO");
}

the config file log4rs.yml:

# Scan this file for changes every 30 seconds
refresh_rate: 30 seconds

appenders:
  # An appender named "stdout" that writes to stdout
  stdout:
    kind: console

  # An appender named "requests" that writes to a file with a custom pattern encoder
  requests:
    kind: file
    path: "requests.log"
    encoder:
      pattern: "{d} - {m}{n}"

# Set the default logging level to "warn" and attach the "stdout" appender to the root
root:
  level: warn
  appenders:
    - stdout

loggers:
  # Raise the maximum log level for events sent to the "app::backend::db" logger to "info"
  app::backend::db:
    level: info

  # Route log events sent to the "app::requests" logger to the "requests" appender,
  # and *not* the normal appenders installed at the root
  app::requests:
    level: info
    appenders:
      - requests
    additive: false

Upvotes: 1

Views: 3712

Answers (1)

Stargateur
Stargateur

Reputation: 26747

When you type cargo run, your working directory is the current directory. This means that all your relative paths will depend on this working directory.

For example, if you are in your home directory (~) and you have your project folder named foo. When you go in it, that gives you ~/foo. If you now type cargo run, that means that when log4rs tries to open your file it will try to open the file ~/foo/log4rs.yml. The file is not here but in ~/foo/src/log4rs.yml

You have many solutions:

  • log4rs::init_file("src/log4rs.yml", Default::default()).unwrap();
  • move log4rs.yml to foo
  • use an absolute path (not a good solution for your current case)

Upvotes: 4

Related Questions