### Basic Installation and Configuration for Onlylogs Rails Engine Source: https://context7.com/renuo/onlylogs/llms.txt Demonstrates how to install the Onlylogs gem, mount the engine in routes, and configure basic settings like authentication credentials, allowed log files, default log path, editor preference, and search result limits. It also shows alternative configuration methods using environment variables and Rails credentials. ```ruby # Gemfile gem "onlylogs" # config/routes.rb Rails.application.routes.draw do mount Onlylogs::Engine, at: "/onlylogs" end # config/initializers/onlylogs.rb Onlylogs.configure do |config| # Basic authentication (required by default) config.basic_auth_user = "admin" config.basic_auth_password = "secure_password" # Configure allowed log files (defaults to log/#{Rails.env}.log) config.allowed_files = [ Rails.root.join("log/development.log"), Rails.root.join("log/production.log"), Rails.root.join("log/*.log"), # Glob patterns supported Rails.root.join("log/**/*.log") # Recursive patterns ] # Set default log file config.default_log_file_path = Rails.root.join("log/#{Rails.env}.log").to_s # Configure editor for clickable file paths config.editor = :vscode # :vscode, :sublime, :atom, :rubymine, etc. # Limit search results (prevents memory issues) config.max_line_matches = 100_000 # or nil for unlimited # Enable/disable ripgrep (auto-detects by default) config.ripgrep_enabled = true end ``` ```bash # Alternative: Environment variables export ONLYLOGS_BASIC_AUTH_USER="admin" export ONLYLOGS_BASIC_AUTH_PASSWORD="secure_password" export ONLYLOGS_EDITOR="vscode" # Or Rails credentials (config/credentials.yml.enc) # onlylogs: # basic_auth_user: admin # basic_auth_password: secure_password # editor: vscode ``` -------------------------------- ### Configure Basic Authentication via Environment Variables Source: https://github.com/renuo/onlylogs/blob/main/README.md This example shows how to set up basic authentication for Onlylogs using environment variables. This method takes precedence over Rails credentials. Ensure these variables are set in your server environment. ```bash # env variables export ONLYLOGS_BASIC_AUTH_USER="your_username" export ONLYLOGS_BASIC_AUTH_PASSWORD="your_password" ``` -------------------------------- ### Add Onlylogs Gem to Gemfile Source: https://github.com/renuo/onlylogs/blob/main/README.md This snippet shows how to add the onlylogs gem to your application's Gemfile for installation. After adding the line, you need to run `bundle install`. ```ruby gem "onlylogs" ``` -------------------------------- ### Secure File Path Encryption and Decryption with Onlylogs Source: https://context7.com/renuo/onlylogs/llms.txt Illustrates how to use `Onlylogs::SecureFilePath` to encrypt file paths for secure transmission over WebSockets and decrypt them on the server-side. The example shows the encryption process and how to handle potential `SecurityError` exceptions during decryption. ```ruby # Encrypt file paths for secure WebSocket transmission file_path = Rails.root.join("log/production.log") encrypted = Onlylogs::SecureFilePath.encrypt(file_path) # => "MjB3RTlpT1RreU1UQX..." # Decrypt on the server side (done automatically by LogsChannel) begin decrypted = Onlylogs::SecureFilePath.decrypt(encrypted) # => "/path/to/rails/log/production.log" rescue Onlylogs::SecureFilePath::SecurityError => e # Handle invalid or tampered encrypted paths Rails.logger.error "Security violation: #{e.message}" end ``` -------------------------------- ### Encrypt File Path for WebSocket Streaming Source: https://github.com/renuo/onlylogs/blob/main/README.md This example shows how to use `Onlylogs::SecureFilePath.encrypt` to encrypt a file path. This encrypted path is then used when streaming logs over a WebSocket, ensuring secure access to log files. ```ruby encrypted_path = Onlylogs::SecureFilePath.encrypt("/path/to/your/log/file.log") # Use encrypted_path for WebSocket communication ``` -------------------------------- ### Using Onlylogs::Logger for Structured Logging in Rails Source: https://context7.com/renuo/onlylogs/llms.txt Explains how to configure Rails to use `Onlylogs::Logger` for structured logging. This logger supports tagged logging and custom formatting, outputting logs with timestamps and severity levels. Examples show basic logging and tagged log usage. ```ruby # config/application.rb or config/environments/production.rb config.logger = Onlylogs::Logger.new(Rails.root.join("log/#{Rails.env}.log")) # The logger includes tagged logging and custom formatting # Example usage in your application Rails.logger.info "User logged in" Rails.logger.error "Payment processing failed" Rails.logger.debug "Processing request" # Tagged logging support Rails.logger.tagged("REQUEST_ID") do Rails.logger.info "Starting payment process" Rails.logger.info "Payment completed" end # Output format: # [2025-12-29T10:15:30+00:00] I User logged in # [2025-12-29T10:15:31+00:00] E Payment processing failed ``` -------------------------------- ### Manual Stimulus Controller Registration for Importmap Source: https://github.com/renuo/onlylogs/blob/main/INTEGRATION.md Manually registers the Onlylogs Stimulus controller for Importmap-based Rails 7+ applications. This method uses ES modules and assumes automatic registration is not functioning. ```javascript import LogStreamerController from "onlylogs/log_streamer_controller" application.register("onlylogs--log-streamer", LogStreamerController) ``` -------------------------------- ### Puma Plugin for Onlylogs Sidecar Process Source: https://context7.com/renuo/onlylogs/llms.txt This Ruby code snippet shows how to integrate the Onlylogs sidecar process with Puma, a web server for Ruby. By adding `plugin :onlylogs_sidecar` to `config/puma.rb`, the sidecar automatically starts alongside Puma. The sidecar creates a UNIX socket, receives logs from SocketLogger, forwards them to onlylogs.io, and runs in a background process. ```ruby # config/puma.rb # Automatically starts onlylogs_sidecar alongside Puma plugin :onlylogs_sidecar # The sidecar: # - Creates UNIX socket at tmp/sockets/onlylogs-sidecar.sock # - Receives log messages from SocketLogger # - Forwards logs to onlylogs.io platform # - Runs in background process # - Automatically stops when Puma stops # Manual sidecar execution: # bundle exec onlylogs_sidecar # Configuration via environment: # export ONLYLOGS_SIDECAR_SOCKET="tmp/sockets/onlylogs-sidecar.sock" # export ONLYLOGS_API_KEY="your_api_key" ``` -------------------------------- ### Manual Stimulus Controller Registration for Propshaft Source: https://github.com/renuo/onlylogs/blob/main/INTEGRATION.md Manually registers the Onlylogs Stimulus controller for Propshaft-based Rails applications. This method utilizes dynamic imports for modern JavaScript integration. ```javascript import LogStreamerController from "./onlylogs/log_streamer_controller.js" application.register("onlylogs--log-streamer", LogStreamerController) ``` -------------------------------- ### Manual Stimulus Controller Registration for Sprockets Source: https://github.com/renuo/onlylogs/blob/main/INTEGRATION.md Manually registers the Onlylogs Stimulus controller for Sprockets-based Rails applications. This approach involves requiring the controller and then manually registering it with Stimulus after the DOM is loaded. ```javascript //= require onlylogs/log_streamer_controller document.addEventListener("DOMContentLoaded", function() { if (window.Stimulus && window.Onlylogs && window.Onlylogs.LogStreamerController) { window.Stimulus.register("onlylogs--log-streamer", window.Onlylogs.LogStreamerController) } }) ``` -------------------------------- ### Onlylogs HTTP Controller API for Logs Source: https://context7.com/renuo/onlylogs/llms.txt This Ruby code defines the GET endpoint for the Onlylogs main log viewer interface. It accepts optional parameters for log file path, filtering, max lines, autoscroll, and mode. The controller renders an HTML interface with WebSocket connectivity, syntax highlighting, keyboard shortcuts, and clickable file paths. ```ruby # GET /onlylogs - Main log viewer interface # Parameters: # - log_file_path: (optional) path to log file # - filter: (optional) search pattern # - max_lines: (optional) number of lines to display (default: 100) # - autoscroll: (optional) enable auto-scroll (default: true) # - mode: (optional) "live" or "search" (default: "live") # Example requests: # View default log file (live mode) GET http://localhost:3000/onlylogs # View specific log file with search GET http://localhost:3000/onlylogs?log_file_path=/var/log/app.log&filter=ERROR&mode=search # Search with more lines GET http://localhost:3000/onlylogs?filter=payment.*failed&max_lines=500 # Disable autoscroll GET http://localhost:3000/onlylogs?autoscroll=false # With basic auth curl -u admin:password http://localhost:3000/onlylogs # The controller renders an HTML interface that: # - Connects to LogsChannel via WebSocket # - Displays logs with syntax highlighting # - Supports keyboard shortcuts # - Provides text selection # - Shows clickable file paths # - Indicates search method (ripgrep vs grep) ``` -------------------------------- ### Onlylogs LogLine Object for Parsing Log Data Source: https://context7.com/renuo/onlylogs/llms.txt This Ruby code defines the LogLine object, which represents a single log entry. It provides methods to access the raw line number and text, a formatted line number, and parsed text with HTML escaping, ANSI color conversion, and file path linking. It also includes methods for conversion to an array and an example of processing log lines from a file. ```ruby # LogLine represents a single line from a log file log_line = Onlylogs::LogLine.new(1234, "ERROR: Payment failed") # Access line number and text log_line.number # => 1234 log_line.text # => "ERROR: Payment failed" # Get formatted line number (with thousands separators) log_line.parsed_number # => " 1'234" # Get parsed text (HTML-escaped, ANSI colors converted, file paths linked) log_line.parsed_text # => "ERROR: path/to/file.rb:42" # Convert to array log_line.to_a # => [1234, "ERROR: Payment failed"] # Example: Processing log lines Onlylogs::File.new("/path/to/log").grep("ERROR") do |log_line| puts "#{log_line.parsed_number}: #{log_line.parsed_text}" end ``` -------------------------------- ### CSS for Responsive and Accessible UI Source: https://github.com/renuo/onlylogs/blob/main/test/dummy/public/422.html This CSS code provides styling for the web page, focusing on responsive design, accessibility, and visual presentation. It sets up a grid layout, defines font sizes with clamping for responsiveness, and ensures proper text rendering. It also includes basic styling for links and emphasis. ```css *, *::before, *::after { box-sizing: border-box; } * { margin: 0; } html { font-size: 16px; } body { background: #FFF; color: #261B23; display: grid; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: clamp(1rem, 2.5vw, 2rem); -webkit-font-smoothing: antialiased; font-style: normal; font-weight: 400; letter-spacing: -0.0025em; line-height: 1.4; min-height: 100vh; place-items: center; text-rendering: optimizeLegibility; -webkit-text-size-adjust: 100%; } a { color: inherit; font-weight: 700; text-decoration: underline; text-underline-offset: 0.0925em; } b, strong { font-weight: 700; } i, em { font-style: italic; } main { display: grid; gap: 1em; padding: 2em; place-items: center; text-align: center; } main header { width: min(100%, 12em); } main header svg { height: auto; max-width: 100%; width: 100%; } main article { width: min(100%, 30em); } main article p { font-size: 75%; } main article br { display: none; } @media (min-width: 48em) { main article br { display: inline; } } ``` -------------------------------- ### Configure Custom Parent Controller for Authentication Source: https://github.com/renuo/onlylogs/blob/main/README.md This Ruby code demonstrates how to set up custom authentication logic for Onlylogs by specifying a parent controller in an initializer. This is useful when basic authentication is insufficient. ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| config.disable_basic_authentication = true config.parent_controller = "ApplicationController" # or any other controller end ``` -------------------------------- ### Configure Basic Authentication Programmatically Source: https://github.com/renuo/onlylogs/blob/main/README.md This Ruby code shows how to configure basic authentication for Onlylogs within an initializer file (`config/initializers/onlylogs.rb`). This allows for programmatic control over the authentication credentials. ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| config.basic_auth_user = "your_username" config.basic_auth_password = "your_password" end ``` -------------------------------- ### Mount Onlylogs Engine in routes.rb Source: https://github.com/renuo/onlylogs/blob/main/README.md This code demonstrates how to mount the Onlylogs engine within your Rails application's `routes.rb` file. This makes the engine's routes available at the specified path, typically `/onlylogs`. ```ruby Rails.application.routes.draw do # ... mount Onlylogs::Engine, at: "/onlylogs" ``` -------------------------------- ### Initialize and Watch Log Files Source: https://context7.com/renuo/onlylogs/llms.txt Initializes a log file reader and provides methods to check file properties such as existence, text-based nature, and size. The `watch` method allows for real-time monitoring of new log entries, handling file rotations and incomplete lines. ```ruby # Initialize a log file reader log_file = Onlylogs::File.new( Rails.root.join("log/production.log"), last_position: 0 # Start from beginning ) # Check if file exists and is readable log_file.exist? # => true log_file.text_file? # => true (checks for binary content) log_file.size # => 1048576 (bytes) # Watch for new log entries (blocking, runs in loop) log_file.watch do |new_lines| new_lines.each do |log_line| puts "Line #{log_line.number}: #{log_line.text}" # Formatted: "Line #{log_line.parsed_number}: #{log_line.parsed_text}" end # Returns array of Onlylogs::LogLine objects # Polls every 0.5 seconds # Handles file rotation and incomplete lines end # Move to specific position in file log_file.go_to_position(1024) # Skip to byte position 1024 # Check if a file is text (not binary) Onlylogs::File.text_file?("/path/to/file.log") # => true (checks for null bytes in first 8KB) ``` -------------------------------- ### Simulate Network Latency for Testing - Bash Source: https://github.com/renuo/onlylogs/blob/main/README.md Provides commands to enable, disable, and test network latency simulation for HTTP and WebSocket connections. This tool helps in testing Onlylogs behavior under production-like network conditions. ```bash # Enable latency simulation (120±30ms jitter on port 3000) ./bin/simulate_latency enable # Enable custom latency simulation (150±30ms jitter on port 3000) ./bin/simulate_latency enable 150 # Enable custom latency and jitter (200±50ms jitter on port 3000) ./bin/simulate_latency enable 200/50 # Enable latency simulation on custom port (120±30ms jitter on port 8080) ./bin/simulate_latency enable -p 8080 # Enable custom latency and jitter on custom port (150±50ms jitter on port 8080) ./bin/simulate_latency enable 150/50 -p 8080 # Test the latency ./bin/simulate_latency test # Check current status ./bin/simulate_latency status # Disable and clean up ./bin/simulate_latency disable ``` -------------------------------- ### Configure Allowed Log Files for Access Source: https://github.com/renuo/onlylogs/blob/main/README.md This Ruby code snippet demonstrates how to configure which log files Onlylogs is allowed to access by creating a configuration initializer. This enhances security by explicitly defining accessible log file paths. ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| config.allowed_log_files = [ Rails.root.join("log", "#{Rails.env}.log"), "/var/log/my_app.log" ] end ``` -------------------------------- ### File Access Configuration Checks Source: https://context7.com/renuo/onlylogs/llms.txt Provides methods to check various file access and system configurations. These include verifying if a file path is allowed, retrieving the default log file path, checking basic authentication status, and determining if ripgrep is enabled. ```ruby # Check if a file path is allowed Onlylogs.allowed_file_path?("/var/log/rails/production.log") # => true or false # Get default log file path Onlylogs.default_log_file_path # => "/path/to/rails/log/production.log" # Check if basic auth is configured Onlylogs.basic_auth_configured? # => true # Check if ripgrep is enabled Onlylogs.ripgrep_enabled? # => true # Get configured editor Onlylogs.editor # => :vscode ``` -------------------------------- ### Using Onlylogs::SocketLogger for Remote Logging Source: https://context7.com/renuo/onlylogs/llms.txt Describes how to use `Onlylogs::SocketLogger` to send logs to a local file and remotely via a UNIX socket, typically to an `onlylogs_sidecar` process. It covers configuration via `config/application.rb` or environment variables and highlights its graceful fallback to local logging on socket failures. ```ruby # config/application.rb # Sends logs both to local file and to onlylogs.io via UNIX socket config.logger = Onlylogs::SocketLogger.new( local_fallback: $stdout, socket_path: "tmp/sockets/onlylogs-sidecar.sock" ) # Requires onlylogs_sidecar process running # Start sidecar: bundle exec onlylogs_sidecar # Environment variable configuration # export ONLYLOGS_SIDECAR_SOCKET="tmp/sockets/onlylogs-sidecar.sock" # Usage is identical to regular logger Rails.logger.info "This goes to both local and remote" Rails.logger.error "Error tracked locally and remotely" # Handles socket failures gracefully - falls back to local logging # Automatically reconnects on socket errors ``` -------------------------------- ### File Access Configuration Source: https://context7.com/renuo/onlylogs/llms.txt Provides methods for checking file path permissions, retrieving default log file paths, and verifying the configuration of authentication and editor settings. ```APIDOC ## File Access Configuration ### Description Provides methods for checking file path permissions, retrieving default log file paths, and verifying the configuration of authentication and editor settings. ### Methods - **`Onlylogs.allowed_file_path?(file_path)`** - Checks if a given file path is permitted for access. - Returns `true` if allowed, `false` otherwise. - Example: `Onlylogs.allowed_file_path?("/var/log/rails/production.log")` - **`Onlylogs.default_log_file_path`** - Retrieves the default log file path configured for the application. - Returns a string representing the path. - Example: `Onlylogs.default_log_file_path` - **`Onlylogs.basic_auth_configured?`** - Checks if basic authentication is enabled. - Returns `true` if configured, `false` otherwise. - Example: `Onlylogs.basic_auth_configured?` - **`Onlylogs.ripgrep_enabled?`** - Checks if ripgrep (a faster grep alternative) is enabled for searching. - Returns `true` if enabled, `false` otherwise. - Example: `Onlylogs.ripgrep_enabled?` - **`Onlylogs.editor`** - Gets the configured editor preference. - Returns a symbol representing the editor (e.g., `:vscode`). - Example: `Onlylogs.editor` ``` -------------------------------- ### Search Log Files with Grep Source: https://context7.com/renuo/onlylogs/llms.txt Enables searching within log files using string patterns or regular expressions. Supports searching specific byte ranges for efficiency on large files. Also includes a direct grep method and a utility to check if a line matches a pattern, with ANSI code stripping. ```ruby # Search with string pattern (auto-escaped) log_file = Onlylogs::File.new(Rails.root.join("log/production.log")) log_file.grep("ERROR") do |log_line| puts "#{log_line.number}: #{log_line.text}" end # Search with regex pattern log_file.grep("error|warning|critical", regexp_mode: true) do |log_line| puts "Found at line #{log_line.number}" end # Search specific byte range (useful for large files) log_file.grep( "payment.*failed", regexp_mode: true, start_position: 0, end_position: 1_000_000 # First 1MB only ) do |log_line| puts log_line.text end # Direct grep without file object Onlylogs::Grep.grep( "error", "/path/to/log/file.log", start_position: 0, regexp_mode: false ) do |line_number, content| puts "#{line_number}: #{content}" end # Or collect results in array results = Onlylogs::Grep.grep("error", "/path/to/file.log") # => [[123, "error content"], [456, "another error"]] # Check if a line matches pattern (with ANSI stripping) Onlylogs::Grep.match_line?( "\e[31mERROR: Something failed\e[0m", "ERROR", regexp_mode: false ) # => true (ANSI codes are stripped before matching) ``` -------------------------------- ### HTML Structure for Error Page Source: https://github.com/renuo/onlylogs/blob/main/test/dummy/public/422.html This HTML snippet defines the basic structure for an error page, likely displaying a '422 Unprocessable Entity' message. It includes elements for a header with an SVG logo and an article for the error message text. The structure is designed to be centered and responsive. ```html

The change you wanted was rejected.

Maybe you tried to change something you didn’t have access to. If you’re the application owner check the logs for more information.

``` -------------------------------- ### CSS Styling for 500 Error Page Source: https://github.com/renuo/onlylogs/blob/main/test/dummy/public/500.html This CSS code provides styling for the 500 Internal Server Error page. It sets up responsive typography, layout using CSS Grid, and basic visual styles for elements like links and text. ```css *, *::before, *::after { box-sizing: border-box; } * { margin: 0; } html { font-size: 16px; } body { background: #FFF; color: #261B23; display: grid; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: clamp(1rem, 2.5vw, 2rem); -webkit-font-smoothing: antialiased; font-style: normal; font-weight: 400; letter-spacing: -0.0025em; line-height: 1.4; min-height: 100vh; place-items: center; text-rendering: optimizeLegibility; -webkit-text-size-adjust: 100%; } a { color: inherit; font-weight: 700; text-decoration: underline; text-underline-offset: 0.0925em; } b, strong { font-weight: 700; } i, em { font-style: italic; } main { display: grid; gap: 1em; padding: 2em; place-items: center; text-align: center; } main header { width: min(100%, 12em); } main header svg { height: auto; max-width: 100%; width: 100%; } main article { width: min(100%, 30em); } main article p { font-size: 75%; } main article br { display: none; } @media(min-width: 48em) { main article br { display: inline; } } ``` -------------------------------- ### Verify Allowed File Path Source: https://context7.com/renuo/onlylogs/llms.txt Checks if a given file path is permitted for access. If allowed, it encrypts the path for secure usage. Raises an error if the file path is not in the allowed list. ```ruby if Onlylogs.allowed_file_path?(file_path) # Safe to access encrypted_path = Onlylogs::SecureFilePath.encrypt(file_path) else # Access denied raise "File not in allowed list" end ``` -------------------------------- ### Configure Allowed Log Files with Glob Patterns - Ruby Source: https://github.com/renuo/onlylogs/blob/main/README.md Configures the list of log files that Onlylogs will process. Supports specific files, glob patterns for multiple files, and patterns for subdirectories. Defaults to `log/#{Rails.env}.log` if not configured. ```ruby Onlylogs.configure do |config| config.allowed_files = [ # Default Rails log files Rails.root.join("log/development.log"), Rails.root.join("log/production.log"), Rails.root.join("log/test.log"), # Custom log files Rails.root.join("log/custom.log"), Rails.root.join("log/api.log"), # Application-specific logs Rails.root.join("log/background_jobs.log"), Rails.root.join("log/imports.log"), # Allow all .log files in a directory using glob patterns Rails.root.join("log/*.log"), Rails.root.join("tmp/logs/*.log") ] end ``` ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| config.allowed_files = [ # Allow all .log files in the log directory Rails.root.join("log/*.log"), # Allow specific pattern matches Rails.root.join("log/*production*.log"), Rails.root.join("log/*development*.log"), # Allow files in subdirectories Rails.root.join("log/**/*.log"), Rails.root.join("tmp/**/*.log") ] end ``` -------------------------------- ### Server-side LogsChannel Implementation Source: https://context7.com/renuo/onlylogs/llms.txt Details the functionalities handled by the `LogsChannel` on the server-side, including live log streaming (tail -f style) and search operations using grep or ripgrep. It also outlines automatic processes like decryption, validation, file type checks, and ANSI code parsing. ```ruby # In your Rails application, the LogsChannel handles: # 1. Live mode - tail -f style streaming # Watches file for new content and streams in real-time # Polls every 0.5 seconds for new lines # 2. Search mode - grep through entire file # Uses ripgrep or grep to find matching lines # Sends results in batches for performance # The channel automatically: # - Decrypts and validates encrypted file paths # - Checks file is in allowed_files whitelist # - Verifies file is text (not binary) # - Handles file position tracking # - Parses ANSI color codes # - Creates clickable file path links # - Respects max_line_matches limit ``` -------------------------------- ### Configure Basic Authentication via Rails Credentials Source: https://github.com/renuo/onlylogs/blob/main/README.md This snippet illustrates how to configure basic authentication for Onlylogs using Rails credentials. Store your username and password in the `config/credentials.yml.enc` file under the `onlylogs` key. ```yaml # config/credentials.yml.enc onlylogs: basic_auth_user: your_username basic_auth_password: your_password ``` -------------------------------- ### Client-side LogsChannel Connection Source: https://context7.com/renuo/onlylogs/llms.txt Establishes a WebSocket connection to the `LogsChannel` for real-time log streaming. It handles connection establishment, receiving data, and sending initialization or stop commands for log watchers. ```javascript // Client-side: Connect to LogsChannel import consumer from "./consumer" const channel = consumer.subscriptions.create("Onlylogs::LogsChannel", { connected() { // Connection established console.log("Connected to logs channel") }, received(data) { // Handle different action types switch(data.action) { case "append_logs": // Live mode: new log lines data.lines.forEach(line => { console.log(`Line ${line.line_number}: ${line.html}`) }) break case "message": // Status messages console.log(data.content) break case "finish": // Search completed console.log(data.content) break case "error": // Error occurred console.error(data.content) break } } }) // Initialize watcher with encrypted file path const encryptedPath = "MjB3RTlpT1RreU1UQX..." // From server channel.perform("initialize_watcher", { file_path: encryptedPath, cursor_position: 0, mode: "live", // or "search" filter: "", // search pattern (search mode only) regexp_mode: false, // true for regex search start_position: 0, // byte offset for search end_position: null // optional end byte for search }) // Stop watching channel.perform("stop_watcher", {}) ``` -------------------------------- ### Puma Plugin for Sidecar Process Source: https://context7.com/renuo/onlylogs/llms.txt Information on integrating the Onlylogs sidecar process with Puma for log forwarding. ```APIDOC ## Puma Plugin for Sidecar Process ### Description Integrates the `onlylogs_sidecar` with the Puma web server to automatically start a background process for forwarding logs. ### Configuration Add the following line to your `config/puma.rb` file: ```ruby plugin :onlylogs_sidecar ``` ### Sidecar Functionality - Creates a UNIX socket at `tmp/sockets/onlylogs-sidecar.sock`. - Receives log messages from `SocketLogger`. - Forwards logs to the `onlylogs.io` platform. - Runs as a background process and stops automatically when Puma stops. ### Manual Execution To run the sidecar manually: ```bash bundle exec onlylogs_sidecar ``` ### Environment Variables Configuration can be managed via environment variables: - `ONLYLOGS_SIDECAR_SOCKET`: Specifies the path for the UNIX socket (defaults to `tmp/sockets/onlylogs-sidecar.sock`). - `ONLYLOGS_API_KEY`: Your API key for the `onlylogs.io` platform. ``` -------------------------------- ### Configure Code Editor for File Path Links - Ruby Source: https://github.com/renuo/onlylogs/blob/main/README.md Sets the preferred code editor for Onlylogs programmatically within the application's initializers. This allows for dynamic or conditional editor configuration. ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| config.editor = :vscode end ``` -------------------------------- ### Configure Code Editor for File Path Links - Environment Variables Source: https://github.com/renuo/onlylogs/blob/main/README.md Sets the preferred code editor for Onlylogs to use when converting file paths in log messages to clickable links. Environment variables can be used to define this setting. ```bash # env variables export EDITOR="vscode" export RAILS_EDITOR="vscode" export ONLYLOGS_EDITOR="vscode" # highest precedence ``` -------------------------------- ### Configure Code Editor for File Path Links - YAML Source: https://github.com/renuo/onlylogs/blob/main/README.md Configures the preferred code editor for Onlylogs using a YAML configuration file. This allows for setting editor preferences alongside other application settings. ```yaml # config/credentials.yml.enc onlylogs: editor: vscode ``` -------------------------------- ### Log File Operations API Source: https://context7.com/renuo/onlylogs/llms.txt API for interacting with log files, including initialization, checking file properties, watching for new entries, and performing searches. ```APIDOC ## Log File Operations API ### Reading and Watching Log Files #### Description Methods for initializing a log file reader, checking file status, and streaming new log entries as they appear. #### Initialization and File Status - **`Onlylogs::File.new(file_path, last_position: 0)`** - Initializes a new log file reader. - `file_path`: The path to the log file. - `last_position`: Optional. The byte offset to start reading from (defaults to 0, beginning of the file). - Example: `log_file = Onlylogs::File.new(Rails.root.join("log/production.log"), last_position: 0)` - **`log_file.exist?`** - Checks if the log file exists. - Returns `true` if the file exists, `false` otherwise. - **`log_file.text_file?`** - Checks if the file is a text file (not binary). - Returns `true` if it's likely a text file, `false` otherwise. - Example: `log_file.text_file?` - **`log_file.size`** - Returns the size of the log file in bytes. - Example: `log_file.size` #### Watching for New Entries - **`log_file.watch do |new_lines| # Process new_lines end`** - Continuously watches the file for new log entries. - This is a blocking operation that runs in a loop. - `new_lines`: An array of `Onlylogs::LogLine` objects containing new entries. - Handles file rotation and incomplete lines. - Polls for new content every 0.5 seconds by default. - Example: `log_file.watch do |new_lines| new_lines.each { |line| puts line.text } end` #### Navigation - **`log_file.go_to_position(byte_position)`** - Moves the reading cursor to a specific byte position within the file. - Example: `log_file.go_to_position(1024)` #### Utility - **`Onlylogs::File.text_file?(file_path)`** - A class method to check if a given file is a text file without creating a file object. - Checks for null bytes in the first 8KB of the file. - Example: `Onlylogs::File.text_file?("/path/to/file.log")` ### Searching Log Files with Grep #### Description Provides functionality to search log files using string patterns or regular expressions, with options for specifying byte ranges. #### Searching with `Onlylogs::File` object - **`log_file.grep(pattern, options = {}) do |log_line| # Process matching log_line end`** - Searches the log file for lines matching the given `pattern`. - `pattern`: The string or regex pattern to search for. - `options`: - `regexp_mode`: (Boolean) Set to `true` to treat `pattern` as a regular expression. - `start_position`: (Integer) Byte offset to start searching from. - `end_position`: (Integer, optional) Byte offset to stop searching at. - Yields `Onlylogs::LogLine` objects that match the pattern. - Example (string search): `log_file.grep("ERROR") { |line| puts line.text }` - Example (regex search): `log_file.grep("error|warning", regexp_mode: true) { |line| puts line.number }` - Example (byte range search): `log_file.grep("payment.*failed", regexp_mode: true, start_position: 0, end_position: 1_000_000)` #### Direct Grep with `Onlylogs::Grep` - **`Onlylogs::Grep.grep(pattern, file_path, options = {}) do |line_number, content| # Process match end`** - Performs a grep operation directly on a file path without needing a `Onlylogs::File` object. - `pattern`: The string or regex pattern. - `file_path`: The path to the log file. - `options`: - `start_position`: (Integer) Byte offset to start searching from. - `regexp_mode`: (Boolean) Set to `true` to treat `pattern` as a regular expression. - Yields `line_number` (Integer) and `content` (String) for each match. - Example: `Onlylogs::Grep.grep("error", "/path/to/log/file.log") { |num, content| puts "#{num}: #{content}" }` - **`Onlylogs::Grep.grep(pattern, file_path, options = {})`** - When called without a block, returns an array of matches. - Returns: `[[line_number, content], ...]` - Example: `results = Onlylogs::Grep.grep("error", "/path/to/file.log")` #### Line Matching Utility - **`Onlylogs::Grep.match_line?(line, pattern, options = {})`** - Checks if a single line matches the given pattern, automatically stripping ANSI color codes before matching. - `line`: The string content of the line to check. - `pattern`: The string or regex pattern. - `options`: - `regexp_mode`: (Boolean) Set to `true` to treat `pattern` as a regular expression. - Returns `true` if the line matches, `false` otherwise. - Example: `Onlylogs::Grep.match_line?("\e[31mERROR: Something failed\e[0m", "ERROR", regexp_mode: false)` ``` -------------------------------- ### HTML Structure for 500 Error Page Source: https://github.com/renuo/onlylogs/blob/main/test/dummy/public/500.html This HTML code defines the structure for the 500 Internal Server Error page. It includes semantic elements for layout and content, along with a message for the user. ```html 500 Internal Server Error

We’re sorry, but something went wrong.

If you’re the application owner check the logs for more information.

``` -------------------------------- ### Accessing Logs from Rails Controller Source: https://context7.com/renuo/onlylogs/llms.txt This Ruby code demonstrates how to access and encrypt log file paths within a Rails controller. It utilizes Rails.root to construct the file path and Onlylogs::SecureFilePath.encrypt to secure it before passing it for potential JavaScript use. ```ruby class MyController < ApplicationController def show_logs file_path = Rails.root.join("log/production.log") @encrypted_path = Onlylogs::SecureFilePath.encrypt(file_path) # Pass @encrypted_path to JavaScript for WebSocket connection end end ``` -------------------------------- ### LogLine Object Source: https://context7.com/renuo/onlylogs/llms.txt Represents a single line from a log file and provides methods for accessing and parsing its content. ```APIDOC ## LogLine Object ### Description Represents a single line from a log file with methods to access line number and text, and to parse the text for display purposes. ### Methods - **new(number, text)**: Initializes a new LogLine object. - **number**: Returns the original line number. - **text**: Returns the original log line text. - **parsed_number**: Returns the formatted line number with thousands separators. - **parsed_text**: Returns the parsed text, with HTML escaping, ANSI color conversion, and file path linking. - **to_a**: Converts the log line to an array `[number, text]`. ### Example ```ruby log_line = Onlylogs::LogLine.new(1234, "ERROR: Payment failed") puts log_line.parsed_number # => " 1'234" puts log_line.parsed_text # => "ERROR: path/to/file.rb:42" ``` ### Usage Example ```ruby Onlylogs::File.new("/path/to/log").grep("ERROR") do |log_line| puts "#{log_line.parsed_number}: #{log_line.parsed_text}" end ``` ``` -------------------------------- ### Disable Basic Authentication in Development Environment Source: https://github.com/renuo/onlylogs/blob/main/README.md This Ruby code snippet shows how to disable basic authentication entirely for the Onlylogs engine, specifically within the development environment configuration file (`config/environments/development.rb`). This is useful for local development and testing. ```ruby # config/environments/development.rb Onlylogs.configure do |config| config.disable_basic_authentication = true end ``` -------------------------------- ### WebSocket Channel API Source: https://context7.com/renuo/onlylogs/llms.txt API for real-time log streaming using WebSockets (LogsChannel), covering both client-side JavaScript and server-side Rails implementation details. ```APIDOC ## WebSocket Channel API ### LogsChannel for Real-time Streaming #### Description Enables real-time streaming of log data to the client via WebSockets. This section details the client-side JavaScript implementation for connecting and receiving data. #### Client-side Usage (JavaScript) ```javascript // client-side: Connect to LogsChannel import consumer from "./consumer" const channel = consumer.subscriptions.create("Onlylogs::LogsChannel", { connected() { // Connection established console.log("Connected to logs channel") }, received(data) { // Handle different action types switch(data.action) { case "append_logs": // Live mode: new log lines data.lines.forEach(line => { console.log(`Line ${line.line_number}: ${line.html}`) }) break case "message": // Status messages console.log(data.content) break case "finish": // Search completed console.log(data.content) break case "error": // Error occurred console.error(data.content) break } } }) // Initialize watcher with encrypted file path const encryptedPath = "MjB3RTlpT1RreU1UQX..." // From server channel.perform("initialize_watcher", { file_path: encryptedPath, cursor_position: 0, mode: "live", // or "search" filter: "", // search pattern (search mode only) regexp_mode: false, // true for regex search start_position: 0, // byte offset for search end_position: null // optional end byte for search }) // Stop watching channel.perform("stop_watcher", {}) ``` ### Server-side LogsChannel Usage #### Description Details the functionality and responsibilities of the `LogsChannel` on the server-side (Rails application) for managing log streaming. #### Server-side Responsibilities (Ruby) ```ruby # In your Rails application, the LogsChannel handles: # 1. Live mode - tail -f style streaming # Watches file for new content and streams in real-time # Polls every 0.5 seconds for new lines # 2. Search mode - grep through entire file # Uses ripgrep or grep to find matching lines # Sends results in batches for performance # The channel automatically: # - Decrypts and validates encrypted file paths # - Checks file is in allowed_files whitelist # - Verifies file is text (not binary) # - Handles file position tracking # - Parses ANSI color codes # - Creates clickable file path links # - Respects max_line_matches limit ``` ``` -------------------------------- ### LogsController Endpoints Source: https://context7.com/renuo/onlylogs/llms.txt Endpoints for accessing the main log viewer interface and performing log searches. ```APIDOC ## GET /onlylogs ### Description Displays the main log viewer interface. Allows viewing logs in live mode or searching through them. Supports various optional parameters for customization. ### Method GET ### Endpoint /onlylogs ### Parameters #### Query Parameters - **log_file_path** (string) - Optional - Path to the log file to view. - **filter** (string) - Optional - Search pattern to filter log lines. - **max_lines** (integer) - Optional - Maximum number of lines to display (default: 100). - **autoscroll** (boolean) - Optional - Enable or disable auto-scroll (default: true). - **mode** (string) - Optional - Display mode: "live" or "search" (default: "live"). ### Request Example ``` GET http://localhost:3000/onlylogs GET http://localhost:3000/onlylogs?log_file_path=/var/log/app.log&filter=ERROR&mode=search GET http://localhost:3000/onlylogs?filter=payment.*failed&max_lines=500 GET http://localhost:3000/onlylogs?autoscroll=false ``` ### Response #### Success Response (200) - The endpoint renders an HTML interface that connects to LogsChannel via WebSocket, displays logs with syntax highlighting, and supports various interactive features. ``` -------------------------------- ### Custom Authentication Configuration for Onlylogs Source: https://context7.com/renuo/onlylogs/llms.txt Details how to disable basic authentication and implement custom authentication logic for the Onlylogs engine. This involves setting a parent controller and defining an `authenticate_onlylogs_user!` method in the application controller. ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| config.disable_basic_authentication = true config.parent_controller = "ApplicationController" end # app/controllers/application_controller.rb class ApplicationController < ActionController::Base private def authenticate_onlylogs_user! # Custom authentication logic redirect_to login_path unless current_user&.admin? end end ``` -------------------------------- ### Configure Maximum Search Results - Ruby Source: https://github.com/renuo/onlylogs/blob/main/README.md Sets the maximum number of lines Onlylogs will return in search results to prevent memory issues. The limit can be customized or removed entirely for specific use cases. ```ruby # config/initializers/onlylogs.rb Onlylogs.configure do |config| # Set a custom limit (e.g., 50,000 lines) config.max_line_matches = 50_000 # Or remove the limit entirely (use with caution) config.max_line_matches = nil end ``` -------------------------------- ### HTML Structure for 400 Bad Request Error Source: https://github.com/renuo/onlylogs/blob/main/test/dummy/public/400.html The HTML defines the basic structure of the error page, including a header with an SVG logo and an article containing the error message. It uses semantic HTML elements for better accessibility and structure. ```html
...

The server cannot process the request due to a client error (400 Bad Request)

Please check the request and try again. If you’re the application owner check the logs for more information.

``` -------------------------------- ### Define Custom Authentication Method in Parent Controller Source: https://github.com/renuo/onlylogs/blob/main/README.md This Ruby code defines the `authenticate_onlylogs_user!` method within a parent controller (e.g., `ApplicationController`). This method is called by Onlylogs to perform custom user authentication before granting access to logs. ```ruby # app/controllers/application_controller.rb class ApplicationController < ActionController::Base private def authenticate_onlylogs_user! raise unless current_user.can_access_logs? end end ```