A readable, structured and beautiful logging for the terminal
A readable, structured and beautiful logging for the terminal
A readable, structured and beautiful logging for the terminal
TTY::Logger provides independent logging component for TTY toolkit.
Add this line to your application's Gemfile:
gem "tty-logger"And then execute:
$ bundleOr install it yourself as:
$ gem install tty-loggerCreate logger:
logger = TTY::Logger.newAnd log information using any of the logger built-in types:
logger.info "Deployed successfully"
logger.info "Deployed", "successfully"
logger.info { "Dynamically generated info" }Include structured data:
logger.success "Deployed successfully", app: "myapp", env: "prod"
# =>
# ✔ success Deployed successfully app=myapp env=prodAdd metadata information:
logger = TTY::Logger.new do |config|
config.metadata = [:date, :time]
end
logger.info "Deployed successfully", app: "myapp", env: "prod"
# =>
# [2019-07-17] [23:21:55.287] › ℹ info Info about the deploy app=myapp env=prodOr change structured data formatting display to JSON:
logger = TTY::Logger.new do |config|
config.formatter = :json
end
logger.info "Deployed successfully"
# =>
# [2019-07-17] [23:21:55.287] › ℹ info Info about the deploy {"app":"myapp","env":"prod"}There are many logger types to choose from:
debug - logs message at :debug levelinfo - logs message at :info levelsuccess - logs message at :info levelwait - logs message at :info levelwarn - logs message at :warn levelerror - logs message at :error levelfatal - logs message at :fatal levelTo log a message, simply choose one of the above types and pass in the actual message. For example, to log successfully deployment at info level do:
logger.success "Deployed successfully"
# =>
# ✔ success Deployed successfullyOr pass in multiple messages:
logger.success "Deployed", "successfully"
# =>
# ✔ success Deployed successfullyYou can delay message evaluation by passing it inside a block:
logger.success { "Dynamically generated info" }
# =>
# ✔ success Dynamically generated infoSimilar to regular logging, you cal split your message into chunks inside a block:
logger.success { ["Dynamically", "generated", "info"] }
# =>
# ✔ success Dynamically generated infoThe above comes handy when paired with structured data.
You can also report on exceptions.
For example, let's say you caught an exception about incorrect data format and use fatal level to log it:
begin
raise ArgumentError, "Wrong data"
rescue => ex
logger.fatal("Error:", ex)
endThis will result in a message followed by a full backtrace:
# =>
# ! fatal Error: Wrong data
# tty-logger/spec/unit/exception_spec.rb:12:in `block (2 levels) in '
# rspec-core-3.8.2/lib/rspec/core/example.rb:257:in `instance_exec'
# rspec-core-3.8.2/lib/rspec/core/example.rb:257:in `block in run'You can define custom log types via the types configuration option:
For example, if you want to add thanks and done log types, you need to provide their names along with logging levels. You can further customise the :console output with your desired styling:
logger = TTY::Logger.new do |config|
config.types = {
thanks: {level: :info},
done: {level: :info}
}
config.handlers = [
[:console, {
styles: {
thanks: {
symbol: "❤️ ",
label: "thanks",
color: :magenta,
levelpad: 0
},
done: {
symbol: "!!",
label: "done",
color: :green,
levelpad: 2
}
}
}]
]
endOnce defined, you can call new log types:
logger.thanks("Great work!")
logger.done("Work done!")
# =>
# ❤️ thanks Great work!
# !! done Work done!The supported levels, ordered by precedence, are:
:debug - for debug-related messages:info - for information of any kind:warn - for warnings:error - for errors:fatal - for fatal conditionsSo the order is: :debug
Or elevate a level to an error with a constant `ERROR_LEVEL`:
```ruby
logger.log_at TTY::Logger::ERROR_LEVEL do
logger.debug("not logged")
logger.error("logged")
end
# =>
# ⨯ error loggedTo add global data available for all logger calls:
logger = TTY::Logger.new(fields: {app: "myapp", env: "prod"})
logger.info("Deploying...")
# =>
# ℹ info Deploying... app=myapp env=prodTo only add data for a single log event:
logger = TTY::Logger.new
logger.wait "Ready to deploy", app: "myapp", env: "prod"
# =>
# … waiting Ready to deploy app=myapp env=prodYou can delay data evaluation until it's evaluated by passing it inside a block:
logger.wait { ["Ready to deploy", {app: "myapp", env: "prod"}] }
# =>
# … waiting Ready to deploy app=myapp env=prod
…
ruby
TTY::Logger.configure do |config|
config.max_bytes = 2**10
config.level = :error
config.metadata = [:time, :date]
endOr if you wish to setup configuration per logger instance use block:
logger = TTY::Logger.new do |config|
config.max_bytes = 2**20
config.metadata = [:all]
endYou can also change the logger's configuration at runtime:
logger.configure do |config|
config.level = :debug
end
…
ruby
logger = TTY::Logger.new(output: output) do |config|
config.filters.message = %w[secret password]
endWhich by default will replace each matching string with [FILTERED] placeholder:
logger.info("Super secret info with password")
# =>
# ℹ info Super [FILTERED] info with [FILTERED]You can also replace each data item with a custom placeholder. To do so use a :mask keyword with a replacement placeholder.
For example, to replace "secret" content with placeholder "" do:
logger = TTY::Logger.new do |config|
config.filters.message = %w[secret]
config.filters.mask = ""
endWhen logged, it will produce:
logger.info("Super secret info")
# =>
# ℹ info Super infoTo filter out sensitive information out of structured data use data method. By default any value matching a parameter name will be filtered regardless of the level of nesting. If you wish to filter only a specific deeply nested key use a dot notation like params.card.password to only filter {params: {card: {password: "Secret123"}}}.
For example to filter out a :password from data do:
logger = TTY::Logger.new do |config|
config.filters.data = %i[password]
endThis will filter out any key matching password:
logger.info("Secret info", password: "Secret123", email: "")
# =>
# ℹ info Secret info password="[FILTERED]" email="secret@example.com"But also any nested data item:
logger.info("Secret info", params: {password: "Secret123", email: ""})
# =>
# ℹ info Secret info params={password="[FILTERED]" email="secret@example.com"}You're not limited to using only direct string comparison. You can also match based on regular expressions. For example, to match keys starting with ba we can add a following filter:
logger = TTY::Logger.new do |config|
config.filters.data = [/ba/]
endThen appropriate values will be masked:
logger.info("Filtering data", {"foo" => {"bar" => "val", "baz" => "val"}})
# =>
# ℹ info Filtering data foo={bar="[FILTERED]" baz="[FILTERED]"}You can mix and match. To filter keys based on pattern inside a deeply nested hash use dot notation with regular expression. For example, to find keys for the :foo parent key that starts with :b character, we could do:
logger = TTY::Logger.new do |config|
config.filters.data = [/^foo\.b/]
endThen only keys under the :foo key will be filtered:
logger.info("Filtering data", {"foo" => {"bar" => "val"}, "baz" => {"bar" => val"}})
# =>
# ℹ info Filtering data foo={bar="[FILTERED]"} baz={bar=val}You can create a copy of a logger with the current configuration using the copy method.
For example, given the following logger with :app and :env data:
logger = TTY::Logger.new(fields: {app: "parent", env: "prod"})We can create a copy with a custom configuration that changes filtered message content and :app data:
child_logger = logger.copy(app: "child") do |config|
config.filters = ["logging"]
endlogger.info("Parent logging")
child_logger.warn("Child logging")
# =>
# ℹ info Parent logging app=parent env=prod
# ⚠ warning Child [FILTERED] app=child env=prodTTY::Logger supports many ways to handle log messages.
The available handlers by default are:
:console - log messages to the console, enabled by default:null - discards any log messages:stream - log messages to an IO stream, a file, a socket or a console.You can also implement your own custom handler.
The handlers can be configured via global or instance configuration with handlers. The handler can be a name or a class name:
TTY::Logger.new do |config|
config.handlers = [:console]
endOr using class name:
TTY::Logger.new do |config|
config.handlers = [TTY::Logger::Handlers::Console]
endHandlers can also be added/removed dynamically through add_handler or remove_handler.
logger = TTY::Logger.new
logger.add_handler(:console)
logger.remove_handler(:console)
…
ruby
logger = TTY::Logger.new
logger.success("Default success")
logger.error("Default error")
# =>
# ✔ success Default success
# ⨯ error Default errorYou can change the default styling with a tuple of handler name and options hash.
In our example, we want to change the styling of success and error:
new_styles = {
styles: {
success: {
symbol: "+",
label: "Ohh yes"
},
error:No open issues yet, or sync has not completed.