What is Sorbet?
Sorbet is a static type checker for Ruby. Static type-checking has many benefits:
- Catches errors at development time, not at runtime
- Ensures consistent log structure
- Provides better IDE documentation and autocompletion
LogStruct is built with Sorbet and provides full type-checking support. We use it to catch errors during development and test and keep the code bug-free.
Adding Sorbet to Your Application
To fully utilize LogStruct's type safety features, you can add Sorbet to your application:
# In your Gemfile
gem "sorbet", group: :development
gem "sorbet-runtime"
Then run:
bundle install
bundle exec srb init
See the Sorbet docs for more details.
Using LogStruct with Sorbet
LogStruct uses predefined log classes with strict typing. This ensures that your logs have a consistent format and that required fields are present and have the right type.
# Create a typed request log entry
request_log = LogStruct::Log::Request.new(
http_method: "GET",
path: "/users",
status: 200,
duration: 45.2,
source: LogStruct::Source::Rails
)
# Log the typed struct at info level
LogStruct.info(request_log)
# Create a typed error log entry
error_log = LogStruct::Log::Error.new(
source: LogStruct::Source::App,
err_class: StandardError,
message: "An error occurred during processing"
)
# Log the error at error level
LogStruct.error(error_log)
Error Handling for Type Errors
LogStruct configures Sorbet error handlers to log and report type-checking errors. If you already use Sorbet and you want to keep using your own error handlers, set enable_sorbet_error_handlers
to false
. This will prevent LogStruct from overriding your handlers.
LogStruct.configure do |config|
config.integrations.enable_sorbet_error_handlers = false
end
Custom Log Classes
You can create your own typed log classes by inheriting from Sorbet's T::Struct
class.
# Define a custom log structure
module TestApp
class Source < T::Enum
enums do
Payments = new
App = new
end
end
class Event < T::Enum
enums do
Processed = new
Failed = new
end
end
module Log
class PaymentProcessed < T::Struct
prop :source, Source
prop :event, Event
prop :timestamp, Time, factory: -> { Time.now }
prop :payment_id, String
prop :amount, Float
prop :currency, String
prop :status, String
prop :user_id, T.nilable(Integer)
end
end
end
T::Struct
subclasses and use Rails.logger
.Built-In Log Classes
Log classes are Typed Structs
under the LogStruct::
module.
Log::ActionMailer
- For email delivery eventsLog::ActiveJob
- For background job executionLog::ActiveStorage
- For file storage operationsLog::CarrierWave
- For CarrierWave upload eventsLog::Error
- For exception details with stack tracesLog::GoodJob
- For GoodJob background job lifecycle eventsLog::Plain
- For general purpose loggingLog::Request
- For HTTP request detailsLog::Security
- For security-related eventsLog::Shrine
- For Shrine file upload eventsLog::Sidekiq
- For Sidekiq job processingLog::SQL
- For ActiveRecord SQL query events and performance metrics
Built-In Enums
Common values are defined as Typed Enums
under the LogStruct::
module.
Level
Log severity levels for different types of log messages
Level::Debug
- Detailed debugging informationLevel::Info
- General informational messagesLevel::Warn
- Warning conditions that should be notedLevel::Error
- Error conditions that affect operationLevel::Fatal
- Severe error conditions that cause the application to terminateLevel::Unknown
- Used when a log level cannot be determined
Source
Sources of log messages to identify which part of the system generated them
Source::TypeChecking
- Type checking errors (Sorbet)Source::LogStruct
- Errors from LogStruct itselfSource::Security
- Security-related events and checksSource::Rails
- Core Rails framework componentsSource::Job
- Background job processingSource::Storage
- ActiveStorage logs and errorsSource::Mailer
- Email delivery and processingSource::App
- Application-specific codeSource::Shrine
- Shrine file upload logs and errorsSource::CarrierWave
- CarrierWave file upload logs and errorsSource::Sidekiq
- Sidekiq background job logs and errors
Event
Event types for different kinds of operations and activities
Event::Log
- Standard log messageEvent::Request
- HTTP requestEvent::Enqueue
- Job added to queueEvent::Schedule
- Job scheduled for future processingEvent::Start
- Job processing startedEvent::Finish
- Job processing completedEvent::Upload
- File upload operationEvent::Download
- File download operationEvent::Delete
- File deletion operationEvent::Metadata
- File metadata operationEvent::Exist
- File existence check operationEvent::Stream
- File streaming operationEvent::Url
- File URL generation operationEvent::Delivery
- Email preparation for deliveryEvent::Delivered
- Email successfully deliveredEvent::IPSpoof
- IP spoofing attack attemptEvent::CSRFViolation
- Cross-Site Request Forgery violationEvent::BlockedHost
- Access attempt from blocked hostEvent::Database
- Database query event and metricsEvent::Error
- Error occurrenceEvent::Unknown
- Unclassified event type
ErrorHandlingMode
Error handling strategies for different types of errors
ErrorHandlingMode::Ignore
- Completely ignore errorsErrorHandlingMode::Log
- Log errors but don't report themErrorHandlingMode::Report
- Log and report errors to error serviceErrorHandlingMode::LogProduction
- Log in production, raise in developmentErrorHandlingMode::ReportProduction
- Report in production without crashing, raise during dev/testErrorHandlingMode::Raise
- Always raise the error (reported by tracking service)