Skip to content

Commit 595065a

Browse files
author
Konstantin
authored
logging: Add possibility to log into file (#2008)
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 <[email protected]>
1 parent 1464801 commit 595065a

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

USAGE.md

+7
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ crystal src/cnf-testsuite.cr <testname>
4747

4848
---
4949

50+
### Logging Parameters
51+
52+
- **LOG_LEVEL** environment variable: sets minimal log level to display: error (default); info; debug.
53+
- **LOG_PATH** environment variable: if set - all logs would be appended to the file defined by that variable.
54+
55+
---
56+
5057
### Common Example Commands
5158

5259
#### Building the executable

spec/utils/utils_spec.cr

+12
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,18 @@ describe "Utils" do
258258
CNFManager.sample_cleanup(config_file: "sample-cnfs/sample-coredns-cnf", verbose: true)
259259
end
260260

261+
it "'logger' should write logs to the file when LOG_PATH is set", tags: ["logger"] do
262+
response_s = `LOG_PATH=spec-test-testsuite.log ./cnf-testsuite test`
263+
$?.success?.should be_true
264+
(/ERROR -- cnf-testsuite: error test/ =~ response_s).should be_nil
265+
File.exists?("spec-test-testsuite.log").should be_true
266+
(/ERROR -- cnf-testsuite: error test/ =~ File.read("spec-test-testsuite.log")).should_not be_nil
267+
ensure
268+
if File.exists?("spec-test-testsuite.log")
269+
File.delete("spec-test-testsuite.log")
270+
end
271+
end
272+
261273
it "'#update_yml' should update the value for a key in a yml file", tags: ["logger"] do
262274
begin
263275
update_yml("spec/fixtures/cnf-testsuite.yml", "release_name", "coredns --set worker-node='kind-control-plane'")

src/tasks/utils/utils.cr

+17-2
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,24 @@ end
8282

8383
# this first line necessary to make sure our custom formatter
8484
# is used in the default error log line also
85-
Log.setup(Log::Severity::Error, Log::IOBackend.new(formatter: log_formatter))
86-
Log.setup(loglevel, Log::IOBackend.new(formatter: log_formatter))
85+
Log.setup(Log::Severity::Error, log_backend)
86+
Log.setup(loglevel, log_backend)
8787

88+
def log_backend
89+
if ENV.has_key?("LOGPATH") || ENV.has_key?("LOG_PATH")
90+
log_file = ENV.has_key?("LOGPATH") ? ENV["LOGPATH"] : ENV["LOG_PATH"]
91+
else
92+
log_file = ""
93+
end
94+
95+
if log_file.empty?
96+
backend = Log::IOBackend.new(formatter: log_formatter)
97+
else
98+
log_io = File.open(log_file, "a")
99+
backend = Log::IOBackend.new(io: log_io, formatter: log_formatter)
100+
end
101+
backend
102+
end
88103

89104
def loglevel
90105
levelstr = "" # default to unset

0 commit comments

Comments
 (0)