百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

tty-logger

> 编程语言
开源

为终端提供可读、结构化且美观的日志记录

293 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

为终端提供可读、结构化且美观的日志记录

TTY::Logger

A readable, structured and beautiful logging for the terminal

TTY::Logger provides independent logging component for TTY toolkit.

Features

  • Intuitive console output for an increased readability
  • Ability to stream data to any IO object
  • Supports structured data logging
  • Filters sensitive data
  • Allows to define custom log types
  • Formats and truncates messages to avoid clogging logging output
  • Customizable styling of labels and symbols for console output
  • Includes metadata information: time, location, scope
  • Handles multiple logging outputs

Installation

Add this line to your application's Gemfile:

ruby
gem "tty-logger"

And then execute:

$ bundle

Or install it yourself as:

$ gem install tty-logger

Contents

  • 1. Usage
  • 2. Synopsis
    • 2.1 Logging
      • 2.1.1 Exceptions
      • 2.1.2 Types
    • 2.2 Levels
      • 2.2.1 Scoped Level
    • 2.3 Structured Data
    • 2.4 Configuration
      • 2.4.1 Metadata
      • 2.4.2 Filters
    • 2.5 Cloning
    • 2.6 Handlers
      • 2.6.1 Console Handler
      • 2.6.2 Stream Handler
      • 2.6.3 Custom Handler
      • 2.6.4 Multiple Handlers
    • 2.7 Formatters
    • 2.8 Output streams
  • 3. Community Extensions
    • 3.1 Sentry Handler

1. Usage

Create logger:

ruby
logger = TTY::Logger.new

And log information using any of the logger built-in types:

ruby
logger.info "Deployed successfully"
logger.info "Deployed", "successfully"
logger.info { "Dynamically generated info" }

Include structured data:

ruby
logger.success "Deployed successfully", app: "myapp", env: "prod"
# =>
# ✔ success Deployed successfully     app=myapp env=prod

Add metadata information:

ruby
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=prod

Or change structured data formatting display to JSON:

ruby
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"}

2. Synopsis

2.1 Logging

There are many logger types to choose from:

  • debug - logs message at :debug level
  • info - logs message at :info level
  • success - logs message at :info level
  • wait - logs message at :info level
  • warn - logs message at :warn level
  • error - logs message at :error level
  • fatal - logs message at :fatal level

To 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:

ruby
logger.success "Deployed successfully"
# =>
# ✔ success Deployed successfully

Or pass in multiple messages:

ruby
logger.success "Deployed", "successfully"
# =>
# ✔ success Deployed successfully

You can delay message evaluation by passing it inside a block:

ruby
logger.success { "Dynamically generated info" }
# =>
# ✔ success Dynamically generated info

Similar to regular logging, you cal split your message into chunks inside a block:

ruby
logger.success { ["Dynamically", "generated", "info"] }
# =>
# ✔ success Dynamically generated info

The above comes handy when paired with structured data.

2.1.1 Exceptions

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:

ruby
begin
  raise ArgumentError, "Wrong data"
rescue => ex
  logger.fatal("Error:", ex)
end

This will result in a message followed by a full backtrace:

ruby
# =>
# ! 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'

2.1.2 Types

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:

ruby
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
        }
      }
    }]
  ]
end

Once defined, you can call new log types:

ruby
logger.thanks("Great work!")
logger.done("Work done!")
# =>
# ❤️  thanks Great work!
# !! done   Work done!

2.2 Levels

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 conditions

So the order is: :debug

• debug logged


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   logged

2.3 Structured data

To add global data available for all logger calls:

ruby
logger = TTY::Logger.new(fields: {app: "myapp", env: "prod"})

logger.info("Deploying...")
# =>
# ℹ info    Deploying...              app=myapp env=prod

To only add data for a single log event:

ruby
logger = TTY::Logger.new
logger.wait "Ready to deploy", app: "myapp", env: "prod"
# =>
# … waiting Ready to deploy           app=myapp env=prod

You can delay data evaluation until it's evaluated by passing it inside a block:

ruby
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]
end

Or if you wish to setup configuration per logger instance use block:

ruby
logger = TTY::Logger.new do |config|
  config.max_bytes = 2**20
  config.metadata = [:all]
end

You can also change the logger's configuration at runtime:

ruby
logger.configure do |config|
  config.level = :debug
end

…

ruby
logger = TTY::Logger.new(output: output) do |config|
  config.filters.message = %w[secret password]
end

Which by default will replace each matching string with [FILTERED] placeholder:

ruby
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:

ruby
logger = TTY::Logger.new do |config|
  config.filters.message = %w[secret]
  config.filters.mask = ""
end

When logged, it will produce:

ruby
logger.info("Super secret info")
# =>
# ℹ info    Super  info

To 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:

ruby
logger = TTY::Logger.new do |config|
  config.filters.data = %i[password]
end

This will filter out any key matching password:

ruby
logger.info("Secret info", password: "Secret123", email: "")
# =>
# ℹ info    Secret info     password="[FILTERED]" email="secret@example.com"

But also any nested data item:

ruby
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:

ruby
logger = TTY::Logger.new do |config|
  config.filters.data = [/ba/]
end

Then appropriate values will be masked:

ruby
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:

ruby
logger = TTY::Logger.new do |config|
  config.filters.data = [/^foo\.b/]
end

Then only keys under the :foo key will be filtered:

ruby
logger.info("Filtering data", {"foo" => {"bar" => "val"}, "baz" => {"bar" => val"}})
# =>
# ℹ info    Filtering data            foo={bar="[FILTERED]"} baz={bar=val}

2.5 Cloning

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:

ruby
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:

ruby
child_logger = logger.copy(app: "child") do |config|
  config.filters = ["logging"]
end
ruby
logger.info("Parent logging")
child_logger.warn("Child logging")
# =>
# ℹ info    Parent logging            app=parent env=prod
# ⚠ warning Child [FILTERED]          app=child env=prod

2.6 Handlers

TTY::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:

ruby
TTY::Logger.new do |config|
  config.handlers = [:console]
end

Or using class name:

ruby
TTY::Logger.new do |config|
  config.handlers = [TTY::Logger::Handlers::Console]
end

Handlers can also be added/removed dynamically through add_handler or remove_handler.

ruby
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 error

You 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:

ruby
new_styles = {
  styles: {
    success: {
      symbol: "+",
      label: "Ohh yes"
    },
    error:

Issues· 4 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyloggerloggingrubyrubygem

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言