From b5e58aba2085d02350fd5121d4af1699b9359063 Mon Sep 17 00:00:00 2001 From: Konstantin Yarovoy Date: Fri, 26 Apr 2024 16:22:22 +0000 Subject: [PATCH] logging: Add possibility to log into file Add processing of environment variables LOGPATH and LOG_PATH If either one exists - logger will log into the file on that path instead of STDOUT. refs: #2000 Signed-off-by: Konstantin Yarovoy --- spec/utils/utils_spec.cr | 12 ++++++++++++ src/tasks/utils/utils.cr | 19 +++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/spec/utils/utils_spec.cr b/spec/utils/utils_spec.cr index 1dde2ea97..717550c3a 100644 --- a/spec/utils/utils_spec.cr +++ b/spec/utils/utils_spec.cr @@ -268,6 +268,18 @@ describe "Utils" do CNFManager.sample_cleanup(config_file: "sample-cnfs/sample-coredns-cnf", verbose: true) end + it "'logger' should write logs to the file when LOG_PATH is set", tags: ["logger"] do + response_s = `LOG_PATH=spec-test-testsuite.log ./cnf-testsuite test` + $?.success?.should be_true + (/ERROR -- cnf-testsuite: error test/ =~ response_s).should be_nil + File.exists?("spec-test-testsuite.log").should be_true + (/ERROR -- cnf-testsuite: error test/ =~ File.read("spec-test-testsuite.log")).should_not be_nil + ensure + if File.exists?("spec-test-testsuite.log") + File.delete("spec-test-testsuite.log") + end + end + it "'#update_yml' should update the value for a key in a yml file", tags: ["logger"] do begin update_yml("spec/fixtures/cnf-testsuite.yml", "release_name", "coredns --set worker-node='kind-control-plane'") diff --git a/src/tasks/utils/utils.cr b/src/tasks/utils/utils.cr index 73dbe3321..1ba78837d 100644 --- a/src/tasks/utils/utils.cr +++ b/src/tasks/utils/utils.cr @@ -79,9 +79,24 @@ end # this first line necessary to make sure our custom formatter # is used in the default error log line also -Log.setup(Log::Severity::Error, Log::IOBackend.new(formatter: log_formatter)) -Log.setup(loglevel, Log::IOBackend.new(formatter: log_formatter)) +Log.setup(Log::Severity::Error, log_backend) +Log.setup(loglevel, log_backend) +def log_backend + if ENV.has_key?("LOGPATH") || ENV.has_key?("LOG_PATH") + log_file = ENV.has_key?("LOGPATH") ? ENV["LOGPATH"] : ENV["LOG_PATH"] + else + log_file = "" + end + + if log_file.empty? + backend = Log::IOBackend.new(formatter: log_formatter) + else + log_io = File.open(log_file, "a") + backend = Log::IOBackend.new(io: log_io, formatter: log_formatter) + end + backend +end def loglevel levelstr = "" # default to unset