How do I Log to multiple files within the same app (e.g.: log to tmp/Foo.log
and tmp/Bar.log
)? In the, the following example code, blank file will be created for each of the log files, but all log entries get logged to the last Logger’s file (e.g.: tmp/Bar.log
). However, I want the LoggerFoo.*(..)
calls to go to the tmp/Foo.log
file and the LoggerBar.*(..)
calls to go to the tmp/Bar.log
file.
require "log"
class LoggerFoo < Log
setup(:info, Log::IOBackend.new(File.new("tmp/Foo.log", "a+")))
end
class LoggerBar < Log
setup(:info, Log::IOBackend.new(File.new("tmp/Bar.log", "a+")))
end
i = 0
LoggerFoo.notice { ["notice", i += 1] }
LoggerBar.warn { ["warn", i += 1] }
LoggerBar.notice { ["notice", i += 1] }
LoggerFoo.warn { ["warn", i += 1] }
tmp/Foo.log
:
tmp/Bar.log
:
2021-10-12T00:31:14.900363Z NOTICE - ["notice", 1]
2021-10-12T00:31:14.900372Z WARN - ["warn", 2]
2021-10-12T00:31:14.900375Z NOTICE - ["notice", 3]
2021-10-12T00:31:14.900378Z WARN - ["warn", 4]
Can use a Log::BroadcastBackend - Crystal 1.2.0-dev with 2 Log::IOBackend
s.
EDIT: You need to create a logger for each source, then bind each source to its related backend. Something like:
FOO_LOGGER = Log.for "foo"
BAR_LOGGER = Log.for "bar"
Log.setup do |c|
foo_backend = Log::IOBackend.new(File.new("tmp/Foo.log", "a+"))
bar_backend = Log::IOBackend.new(File.new("tmp/Bar.log", "a+"))
c.bind "foo.*", :info, foo_backend
c.bind "bar.*", :info, bar_backend
end
1 Like
@Blacksmoke16 , Thanks! 
Now my example looks like:
require "log"
FOO_LOGGER = Log.for "foo"
BAR_LOGGER = Log.for "bar"
Log.setup do |c|
foo_backend = Log::IOBackend.new(File.new("tmp/Foo.log", "a+"))
bar_backend = Log::IOBackend.new(File.new("tmp/Bar.log", "a+"))
c.bind "foo.*", :info, foo_backend
c.bind "bar.*", :info, bar_backend
end
i = 0
FOO_LOGGER.notice { ["notice", i += 1] }
BAR_LOGGER.warn { ["warn", i += 1] }
BAR_LOGGER.notice { ["notice", i += 1] }
FOO_LOGGER.warn { ["warn", i += 1] }
And, after clearing my log file contents,
- the
tmp/Foo.log
file looks like:
2021-10-12T00:58:43.165283Z NOTICE - foo: ["notice", 1]
2021-10-12T00:58:43.165302Z WARN - foo: ["warn", 4]
- the
tmp/Bar.log
(after I cleared the contents) looks like:
2021-10-12T00:58:43.165294Z WARN - bar: ["warn", 2]
2021-10-12T00:58:43.165298Z NOTICE - bar: ["notice", 3]
2 posts were split to a new topic: Log Rotation