tailer

package module
v0.0.0-...-8f0486b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

README

Tailer

A cross-platform Go library for tailing files, similar to the Unix tail -F command. It monitors files for changes and supports log rotation, truncation, and pattern filtering.

Features

  • 📝 Real-time file tailing: Monitor files for new content as they grow
  • 🔄 Log rotation detection: Automatically detects when files are rotated and follows the new file
  • ✂️ Truncation handling: Detects when files are truncated and starts from the beginning
  • 🔍 Pattern filtering: Filter lines using regular expressions (grep-like functionality)
  • 📂 Multi-file tailing: Tail multiple files simultaneously with MultiTail
  • 🌐 Web interface: Built-in HTTP handler with SSE (Server-Sent Events) for browser-based tailing
  • 🖥️ Terminal UI: Includes xterm.js-based web terminal with syntax highlighting
  • 🎨 Customizable themes: Multiple predefined color themes for web terminal
  • 🪟 Cross-platform: Works on Windows, Linux, macOS, and BSD systems
  • Efficient: Uses polling with configurable intervals
  • 🎯 Flexible: Read last N lines before starting to tail

Installation

go get github.com/OutOfBedlam/tailer

Usage

Basic Example
package main

import (
    "fmt"
    "time"
    
    "github.com/OutOfBedlam/tailer"
)

func main() {
    // Create a new tailer
    tail := tailer.New("/var/log/app.log")
    
    // Start tailing
    if err := tail.Start(); err != nil {
        panic(err)
    }
    defer tail.Stop()
    
    // Read lines from the channel
    for line := range tail.Lines() {
        fmt.Println(line)
    }
}
Custom Configuration
tail := tailer.New("/var/log/app.log",
    tailer.WithPollInterval(500*time.Millisecond),  // Check file every 500ms
    tailer.WithBufferSize(200),                     // Channel buffer size
    tailer.WithLast(20),                           // Show last 20 lines on start
)
Pattern Filtering (Grep)

Filter lines using regular expressions. Multiple patterns can be specified:

// Show only error and warning lines
tail := tailer.New("/var/log/app.log",
    tailer.WithPattern("error", "warning"),  // Lines matching both "error" AND "warning"
    tailer.WithPattern("fatal"),             // OR lines matching "fatal"
)

if err := tail.Start(); err != nil {
    panic(err)
}
defer tail.Stop()

for line := range tail.Lines() {
    fmt.Println(line)  // Only lines matching the patterns
}

Pattern groups work as follows:

  • Within a WithPattern() call, all patterns must match (AND logic)
  • Multiple WithPattern() calls are OR'ed together
  • Example: WithPattern("error", "thing") matches lines containing both "error" AND "thing"
  • Example: Multiple calls like WithPattern("error") and WithPattern("warning") match lines with "error" OR "warning"
Complete Example with Timeout
package main

import (
    "fmt"
    "time"
    
    "github.com/OutOfBedlam/tailer"
)

func main() {
    tail := tailer.New("/var/log/app.log",
        tailer.WithPollInterval(100*time.Millisecond),
        tailer.WithLast(10),
        tailer.WithPattern("ERROR"),
    )
    
    if err := tail.Start(); err != nil {
        panic(err)
    }
    defer tail.Stop()
    
    timeout := time.After(30 * time.Second)
    
    for {
        select {
        case line := <-tail.Lines():
            fmt.Printf("[%s] %s\n", time.Now().Format("15:04:05"), line)
        case <-timeout:
            fmt.Println("Tailing complete")
            return
        }
    }
}
Multi-File Tailing

You can tail multiple files simultaneously using NewMultiTail(). Each line will be prefixed with the file's alias for identification.

package main

import (
    "fmt"
    "time"
    
    "github.com/OutOfBedlam/tailer"
)

func main() {
    // Create individual tails with custom aliases
    tail1 := tailer.New("/var/log/app.log",
        tailer.WithAlias("app"),
        tailer.WithPattern("ERROR"),
    )
    
    tail2 := tailer.New("/var/log/system.log",
        tailer.WithAlias("system"),
        tailer.WithPattern("WARN"),
    )
    
    // Combine them into a MultiTail
    multiTail := tailer.NewMultiTail(tail1, tail2)
    
    if err := multiTail.Start(); err != nil {
        panic(err)
    }
    defer multiTail.Stop()
    
    // Lines are prefixed with aligned aliases
    for line := range multiTail.Lines() {
        fmt.Println(line)  // Output: "app    ERROR: something" or "system WARN: something"
    }
}

The MultiTail feature:

  • Automatically aligns alias prefixes for clean output
  • Merges lines from all tails into a single channel
  • Maintains individual tail configurations (filters, poll intervals, etc.)
  • Useful for monitoring multiple log files in one view
Web-Based Tailing with SSE

The package includes a built-in HTTP handler that provides real-time log tailing through Server-Sent Events (SSE) with a beautiful web terminal interface.

Simple HTTP Server Example
package main

import (
    "log"
    "net/http"
    
    "github.com/OutOfBedlam/tailer"
)

func main() {
    // Create a terminal with a tail configuration
    terminal := tailer.NewTerminal(
        tailer.WithTail("/var/log/app.log"),
    )
    defer terminal.Close()
    
    // Create handler from terminal
    handler := terminal.Handler("/tail/")
    
    // Mount the handler
    http.Handle("/tail/", handler)
    
    log.Println("Server starting on http://localhost:8080")
    log.Println("Open http://localhost:8080/tail/ in your browser")
    
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}
Advanced HTTP Server with Multiple Files
package main

import (
    "log"
    "net/http"
    
    "github.com/OutOfBedlam/tailer"
)

func main() {
    mux := http.NewServeMux()
    
    // Tail application logs
    appTerminal := tailer.NewTerminal(
        tailer.WithTail("/var/log/myapp.log"),
    )
    defer appTerminal.Close()
    mux.Handle("/logs/app/", appTerminal.Handler("/logs/app/"))
    
    // Tail access logs
    accessTerminal := tailer.NewTerminal(
        tailer.WithTail("/var/log/access.log"),
    )
    defer accessTerminal.Close()
    mux.Handle("/logs/access/", accessTerminal.Handler("/logs/access/"))
    
    // Tail error logs
    errorTerminal := tailer.NewTerminal(
        tailer.WithTail("/var/log/error.log"),
    )
    defer errorTerminal.Close()
    mux.Handle("/logs/error/", errorTerminal.Handler("/logs/error/"))
    
    log.Println("Multi-log viewer starting on :8080")
    log.Println("Available endpoints:")
    log.Println("  - http://localhost:8080/logs/app/")
    log.Println("  - http://localhost:8080/logs/access/")
    log.Println("  - http://localhost:8080/logs/error/")
    
    if err := http.ListenAndServe(":8080", mux); err != nil {
        log.Fatal(err)
    }
}
Graceful Shutdown
package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
    
    "github.com/OutOfBedlam/tailer"
)

func main() {
    terminal := tailer.NewTerminal(
        tailer.WithTail("/var/log/app.log"),
    )
    defer terminal.Close()
    
    server := &http.Server{
        Addr:    ":8080",
        Handler: terminal.Handler("/"),
    }
    
    // Start server in goroutine
    go func() {
        log.Println("Server starting on :8080")
        if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Server error: %v", err)
        }
    }()
    
    // Wait for interrupt signal
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit
    
    log.Println("Shutting down server...")
    
    // Gracefully shutdown HTTP server
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    if err := server.Shutdown(ctx); err != nil {
        log.Fatalf("Server forced to shutdown: %v", err)
    }
    
    log.Println("Server stopped")
}
Web Interface Features

The built-in web interface includes:

  • xterm.js terminal: Full-featured terminal emulator in the browser
  • Syntax highlighting: Configurable colorization via WithSyntaxColoring() option
  • Real-time updates: Server-Sent Events (SSE) push new lines instantly
  • Filter support: Query parameter filtering with AND/OR logic
  • Responsive design: Works on desktop and mobile browsers
  • Auto-scrolling: Terminal automatically scrolls to show new content
  • Multiple file support: Tail multiple files simultaneously with MultiTail
URL Filter Parameters

You can filter log lines using URL query parameters:

# Filter for lines containing "error"
http://localhost:8080/tail/?filter=error

# Filter for lines containing both "error" AND "database" (AND logic with &&)
http://localhost:8080/tail/?filter=error&&database

# Filter for lines with "error" OR "warning" (OR logic with ||)
http://localhost:8080/tail/?filter=error||warning

# Complex filter: (error AND database) OR (warning AND timeout)
http://localhost:8080/tail/?filter=error&&database||warning&&timeout

Filter syntax:

  • && = AND operator (all patterns must match)
  • || = OR operator (any pattern group can match)
  • Patterns are regular expressions

API Reference

Types
type Tail

The main tailer instance that monitors a file.

Functions
New(filepath string, opts ...Option) *Tail

Creates a new Tail instance for the specified file path.

Default values:

  • Poll interval: 1 second
  • Buffer size: 100 lines
  • Last N lines: 10
(*Tail) Start() error

Starts tailing the file. Reads the last N lines (configurable) and then monitors for new content.

(*Tail) Stop() error

Stops tailing and closes the file. This method waits for the internal goroutine to finish before returning.

(*Tail) Lines() <-chan string

Returns a read-only channel that outputs new lines from the file.

NewTerminal(opts ...TerminalOption) Terminal

Creates a new Terminal instance with customizable options for web-based log viewing.

Returns: A Terminal that can be used to create HTTP handlers

Example:

terminal := tailer.NewTerminal(
    tailer.WithTail("/var/log/app.log"),
    tailer.WithFontSize(14),
    tailer.WithTheme(tailer.ThemeUbuntu),
)
defer terminal.Close()
(*Terminal) Handler(cutPrefix string) Handler

Creates an HTTP handler from the terminal configuration.

Parameters:

  • cutPrefix: The URL prefix to strip from incoming requests (e.g., "/logs/")

Returns: An http.Handler that serves:

  • A web interface at the base URL (using embedded xterm.js terminal)
  • An SSE stream at {baseURL}/watch.stream for real-time log updates

The handler automatically:

  • Polls files every 500ms for changes
  • Uses a buffer size of 1000 lines
  • Supports URL query parameter filtering via ?filter=

Example:

terminal := tailer.NewTerminal(tailer.WithTail("/var/log/app.log"))
handler := terminal.Handler("/logs/")
http.Handle("/logs/", handler)
(*Terminal) Close()

Stops any active watchers and signals all SSE connections to close. Call this during graceful shutdown.

Example:

terminal := tailer.NewTerminal(tailer.WithTail("/var/log/app.log"))
defer terminal.Close()
NewMultiTail(tails ...ITail) ITail

Creates a multi-file tailer that merges output from multiple tail instances.

Parameters:

  • tails: Variable number of tail instances to combine

Returns: An ITail interface that merges all tail outputs

Example:

multiTail := tailer.NewMultiTail(tail1, tail2, tail3)
multiTail.Start()
defer multiTail.Stop()
Options
WithPollInterval(d time.Duration) Option

Sets the interval for checking file changes. Lower values provide faster updates but use more CPU.

tailer.WithPollInterval(500 * time.Millisecond)
WithBufferSize(size int) Option

Sets the channel buffer size. Larger buffers can handle bursts of log lines better.

tailer.WithBufferSize(200)
WithLast(n int) Option

Sets how many lines from the end of the file to read when starting.

tailer.WithLast(20)  // Read last 20 lines on start
WithPattern(patterns ...string) Option

Adds a pattern group for filtering lines. Each pattern is a regular expression. All patterns within a single WithPattern call must match (AND logic). Multiple WithPattern calls are OR'ed together.

// Match lines containing both "error" AND "database"
tailer.WithPattern("error", "database")

// Match lines with "error" OR "warning"
tailer.New(filepath,
    tailer.WithPattern("error"),
    tailer.WithPattern("warning"),
)
WithAlias(alias string) Option

Sets a custom alias for the tail instance. This is particularly useful with MultiTail to identify which file each line came from.

tail := tailer.New("/var/log/application.log",
    tailer.WithAlias("app"),
)

When used with MultiTail, the alias is automatically prefixed to each line with proper alignment.

WithPlugins(plugins...Plugin) Option

Adds one or more plugins to process lines before they are sent to the output channel. Plugins can modify line content (e.g., add ANSI color codes) or drop lines entirely. Each plugin's Apply(line string) (string, bool) method is called in order - if it returns false, the line is dropped and no further plugins are executed.

type Plugin interface {
    // Apply processes a line and returns the modified line
    // and a boolean indicating if processing should continue
    // Return false to drop the line
    Apply(line string) (string, bool)
}
WithSyntaxColoring(syntax ...string) Option

Enable syntax coloring that adds ANSI color codes to specific patterns in log lines. This is particularly useful for enhancing readability of structured logs in terminal displays.

Supported syntax styles:

  • "level", "levels": Colorizes standard log levels

    • TRACE (dark gray), DEBUG (light gray), INFO (green), WARN (yellow), ERROR (red)
  • "slog-text": Colorizes structured logging format (key=value pairs)

    • Keys in cyan, values in blue
  • "slog-json": Colorizes JSON logging format

    • Keys in cyan, values in blue
  • "syslog": Colorizes syslog format (/var/log/syslog)

    • Timestamps in blue, hostnames in cyan, process names in yellow

Examples:

// Colorize log levels only
tail := tailer.New("/var/log/app.log",
    tailer.WithSyntaxColoring("level"),
)

// Colorize both log levels and slog key-value pairs
tail := tailer.New("/var/log/app.log",
    tailer.WithSyntaxColoring("level", "slog-text"),
)

// Colorize syslog format
tail := tailer.New("/var/log/syslog",
    tailer.WithSyntaxColoring("syslog"),
)
Terminal Options

When creating a Terminal for web-based viewing, you can customize its behavior and appearance:

WithTail(filename string, opts ...Option) TerminalOption

Adds a file to tail in the terminal. You can call this multiple times to tail multiple files.

terminal := tailer.NewTerminal(
    tailer.WithTail("/var/log/app.log", tailer.WithPattern("ERROR")),
    tailer.WithTail("/var/log/system.log", tailer.WithPattern("WARN")),
)
WithFontSize(size int) TerminalOption

Sets the terminal font size in pixels.

tailer.WithFontSize(14)
WithFontFamily(family string) TerminalOption

Sets the terminal font family.

tailer.WithFontFamily("Consolas, monospace")
WithScrollback(lines int) TerminalOption

Sets the number of lines to keep in the scrollback buffer.

tailer.WithScrollback(10000)
WithTheme(theme TerminalTheme) TerminalOption

Applies a color theme to the terminal.

tailer.WithTheme(tailer.ThemeUbuntu)
WithTitle(title string) TerminalOption

Sets a custom title for the terminal page.

tailer.WithTitle("Production Logs")
Terminal Themes

When using the web-based terminal interface via Terminal.Handler(), you can customize the terminal appearance using predefined color themes. The terminal uses xterm.js and supports full 16-color ANSI palettes.

Available Themes
  • ThemeDefault: Standard dark theme with good contrast (default)
  • ThemeSolarizedDark: Popular Solarized Dark color scheme
  • ThemeSolarizedLight: Solarized Light for bright environments
  • ThemeMolokai: Vibrant Molokai editor theme
  • ThemeUbuntu: Ubuntu terminal's signature purple theme
  • ThemeDracula: Popular Dracula color scheme
  • ThemeNordic: Nordic/Nord color scheme
Terminal Structure

The Terminal struct allows fine-grained control over terminal behavior and appearance:

type Terminal struct {
    CursorBlink         bool          // Enable/disable cursor blinking
    CursorInactiveStyle string        // Cursor style when terminal is inactive
    CursorStyle         string        // Cursor style: "block", "underline", "bar"
    FontSize            int           // Terminal font size in pixels
    FontFamily          string        // CSS font-family value
    Theme               TerminalTheme // Color theme (see predefined themes)
    Scrollback          int           // Number of lines to keep in scrollback buffer
    DisableStdin        bool          // Disable keyboard input (read-only terminal)
    ConvertEol          bool          // Convert line endings
}

Default terminal settings:

Terminal{
    CursorBlink:  false,
    FontSize:     12,
    FontFamily:   `"Monaspace Neon",ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace`,
    Theme:        ThemeDefault,
    Scrollback:   5000,
    DisableStdin: true, // Terminal is read-only for log viewing
}
TerminalTheme Structure

Each theme defines a complete 16-color ANSI palette plus UI colors:

type TerminalTheme struct {
    Background          string // Terminal background color
    Foreground          string // Default text color
    Cursor              string // Cursor color
    CursorAccent        string // Cursor accent/border color
    SelectionBackground string // Text selection background
    
    // Standard ANSI colors (0-7)
    Black   string
    Red     string
    Green   string
    Yellow  string
    Blue    string
    Magenta string
    Cyan    string
    White   string
    
    // Bright ANSI colors (8-15)
    BrightBlack   string
    BrightRed     string
    BrightGreen   string
    BrightYellow  string
    BrightBlue    string
    BrightMagenta string
    BrightCyan    string
    BrightWhite   string
}

Example - Solarized Dark theme:

var ThemeSolarizedDark = TerminalTheme{
    Background:          "#002b36",
    Foreground:          "#839496",
    Cursor:              "#839496",
    CursorAccent:        "#002b36",
    SelectionBackground: "#073642",
    Black:               "#073642",
    Red:                 "#dc322f",
    Green:               "#859900",
    Yellow:              "#b58900",
    Blue:                "#268bd2",
    Magenta:             "#d33682",
    Cyan:                "#2aa198",
    White:               "#eee8d5",
    // ... bright colors
}

Creating custom themes:

You can define your own themes by creating a TerminalTheme with custom colors:

customTheme := tailer.TerminalTheme{
    Background: "#1a1a1a",
    Foreground: "#e0e0e0",
    Cursor:     "#00ff00",
    Red:        "#ff5555",
    Green:      "#50fa7b",
    Yellow:     "#f1fa8c",
    Blue:       "#bd93f9",
    // ... define all colors
}

How It Works

File Rotation Detection

The tailer detects file rotation by monitoring the file's inode (Unix) or file index (Windows). When a rotation is detected:

  1. It reads any remaining content from the old file
  2. Opens the new file
  3. Continues tailing from the beginning of the new file
Truncation Detection

The tailer detects file truncation by comparing the current file size with the last known size and read position. When truncation is detected, it seeks to the beginning and reads all new content.

Server-Sent Events (SSE) Streaming

The HTTP handler uses Server-Sent Events to push log lines to web browsers in real-time:

  1. Connection: Browser connects to /watch.stream endpoint
  2. Streaming: Server sends each new log line as an SSE data: event
  3. Filtering: Optional filter query parameter applies regex patterns server-side
  4. Colorization: Log levels are automatically wrapped with ANSI color codes for terminal display
  5. Keep-alive: Regular flush operations keep the connection active
  6. Termination: Connection closes on browser disconnect, server shutdown, or context cancellation

The SSE format follows the standard:

data: <log line with ANSI colors>\n\n
Windows Compatibility

On Windows, files are opened with FILE_SHARE_DELETE flag, allowing the file to be renamed or deleted while the tailer has it open. This enables proper log rotation support on Windows.

Platform Support

  • ✅ Windows
  • ✅ Linux
  • ✅ macOS
  • ✅ FreeBSD
  • ✅ OpenBSD
  • ✅ NetBSD

Testing

Run the tests:

go test -v

The test suite includes:

  • Basic tailing functionality
  • Log rotation detection
  • File truncation handling
  • Pattern filtering

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Index

Constants

View Source
const (
	ColorReset         = "\033[0m"
	ColorBlack         = "\033[30m"       // Black
	ColorRed           = "\033[31m"       // Red
	ColorGreen         = "\033[32m"       // Green
	ColorYellow        = "\033[33m"       // Yellow
	ColorBlue          = "\033[34m"       // Blue
	ColorMagenta       = "\033[35m"       // Magenta
	ColorCyan          = "\033[36m"       // Cyan for keys
	ColorLightGray     = "\033[37m"       // Light gray
	ColorNavy          = "\033[38;5;17m"  // Navy
	ColorTeal          = "\033[38;5;51m"  // Teal
	ColorMaroon        = "\033[38;5;52m"  // Maroon
	ColorIndigo        = "\033[38;5;57m"  // Indigo
	ColorLightBlue     = "\033[38;5;81m"  // Light Blue
	ColorBrown         = "\033[38;5;94m"  // Brown
	ColorOlive         = "\033[38;5;100m" // Olive
	ColorLightGreen    = "\033[38;5;120m" // Light Green
	ColorPurple        = "\033[38;5;135m" // Purple
	ColorLime          = "\033[38;5;154m" // Lime
	ColorPink          = "\033[38;5;205m" // Pink
	ColorOrange        = "\033[38;5;208m" // Orange
	ColorGray          = "\033[38;5;245m" // Gray
	ColorDarkGray      = "\033[90m"       // Dark gray
	ColorBrightRed     = "\033[91m"       // Bright Red
	ColorBrightGreen   = "\033[92m"       // Bright Green
	ColorBrightYellow  = "\033[93m"       // Bright Yellow
	ColorBrightBlue    = "\033[94m"       // Bright Blue
	ColorBrightMagenta = "\033[95m"       // Bright Magenta
	ColorBrightCyan    = "\033[96m"       // Bright Cyan
	ColorWhite         = "\033[97m"       // White
)

ANSI color codes

Variables

View Source
var ThemeDefault = TerminalTheme{
	Background:          "#1e1e1e",
	Foreground:          "#ffffff",
	Cursor:              "#ffffff",
	CursorAccent:        "#1e1e1e",
	SelectionBackground: "#264f78",
	Black:               "#000000",
	Red:                 "#cd3131",
	Green:               "#0dbc79",
	Yellow:              "#e5e510",
	Blue:                "#2472c8",
	Magenta:             "#bc3fbc",
	Cyan:                "#11a8cd",
	White:               "#e5e5e5",
	BrightBlack:         "#666666",
	BrightRed:           "#f14c4c",
	BrightGreen:         "#23d18b",
	BrightYellow:        "#f5f543",
	BrightBlue:          "#3b8eea",
	BrightMagenta:       "#d670d6",
	BrightCyan:          "#29b8db",
	BrightWhite:         "#ffffff",
}

ThemeDefault provides a standard dark terminal color scheme

View Source
var ThemeDracula = TerminalTheme{
	Background:          "#282a36",
	Foreground:          "#f8f8f2",
	Cursor:              "#f8f8f2",
	CursorAccent:        "#282a36",
	SelectionBackground: "#44475a",
	Black:               "#21222c",
	Red:                 "#ff5555",
	Green:               "#50fa7b",
	Yellow:              "#f1fa8c",
	Blue:                "#bd93f9",
	Magenta:             "#ff79c6",
	Cyan:                "#8be9fd",
	White:               "#f8f8f2",
	BrightBlack:         "#6272a4",
	BrightRed:           "#ff6e6e",
	BrightGreen:         "#69ff94",
	BrightYellow:        "#ffffa5",
	BrightBlue:          "#d6acff",
	BrightMagenta:       "#ff92df",
	BrightCyan:          "#a4ffff",
	BrightWhite:         "#ffffff",
}

ThemeDracula provides the Dracula color scheme

View Source
var ThemeMolokai = TerminalTheme{
	Background:          "#1b1d1e",
	Foreground:          "#f8f8f2",
	Cursor:              "#f8f8f0",
	CursorAccent:        "#1b1d1e",
	SelectionBackground: "#49483e",
	Black:               "#1b1d1e",
	Red:                 "#f92672",
	Green:               "#a6e22e",
	Yellow:              "#e6db74",
	Blue:                "#66d9ef",
	Magenta:             "#ae81ff",
	Cyan:                "#a1efe4",
	White:               "#f8f8f2",
	BrightBlack:         "#75715e",
	BrightRed:           "#f92672",
	BrightGreen:         "#a6e22e",
	BrightYellow:        "#e6db74",
	BrightBlue:          "#66d9ef",
	BrightMagenta:       "#ae81ff",
	BrightCyan:          "#a1efe4",
	BrightWhite:         "#f9f8f5",
}

ThemeMolokai provides the Molokai color scheme

View Source
var ThemeNordic = TerminalTheme{
	Background:          "#2e3440",
	Foreground:          "#d8dee9",
	Cursor:              "#d8dee9",
	CursorAccent:        "#2e3440",
	SelectionBackground: "#434c5e",
	Black:               "#3b4252",
	Red:                 "#bf616a",
	Green:               "#a3be8c",
	Yellow:              "#ebcb8b",
	Blue:                "#81a1c1",
	Magenta:             "#b48ead",
	Cyan:                "#88c0d0",
	White:               "#e5e9f0",
	BrightBlack:         "#4c566a",
	BrightRed:           "#bf616a",
	BrightGreen:         "#a3be8c",
	BrightYellow:        "#ebcb8b",
	BrightBlue:          "#81a1c1",
	BrightMagenta:       "#b48ead",
	BrightCyan:          "#8fbcbb",
	BrightWhite:         "#eceff4",
}

ThemeNordic provides the Nordic color scheme

View Source
var ThemeSolarizedDark = TerminalTheme{
	Background:          "#002b36",
	Foreground:          "#839496",
	Cursor:              "#839496",
	CursorAccent:        "#002b36",
	SelectionBackground: "#073642",
	Black:               "#073642",
	Red:                 "#dc322f",
	Green:               "#859900",
	Yellow:              "#b58900",
	Blue:                "#268bd2",
	Magenta:             "#d33682",
	Cyan:                "#2aa198",
	White:               "#eee8d5",
	BrightBlack:         "#002b36",
	BrightRed:           "#cb4b16",
	BrightGreen:         "#586e75",
	BrightYellow:        "#657b83",
	BrightBlue:          "#839496",
	BrightMagenta:       "#6c71c4",
	BrightCyan:          "#93a1a1",
	BrightWhite:         "#fdf6e3",
}

ThemeSolarizedDark provides the Solarized Dark color scheme

View Source
var ThemeSolarizedLight = TerminalTheme{
	Background:          "#fdf6e3",
	Foreground:          "#1f4755",
	Cursor:              "#657b83",
	CursorAccent:        "#fdf6e3",
	SelectionBackground: "#eee8d5",
	Black:               "#073642",
	Red:                 "#dc322f",
	Green:               "#859900",
	Yellow:              "#b58900",
	Blue:                "#268bd2",
	Magenta:             "#d33682",
	Cyan:                "#2aa198",
	White:               "#eee8d5",
	BrightBlack:         "#002b36",
	BrightRed:           "#cb4b16",
	BrightGreen:         "#586e75",
	BrightYellow:        "#657b83",
	BrightBlue:          "#839496",
	BrightMagenta:       "#6c71c4",
	BrightCyan:          "#93a1a1",
	BrightWhite:         "#fdf6e3",
}

ThemeSolarizedLight provides the Solarized Light color scheme

View Source
var ThemeUbuntu = TerminalTheme{
	Background:          "#300a24",
	Foreground:          "#ffffff",
	Cursor:              "#ffffff",
	CursorAccent:        "#300a24",
	SelectionBackground: "#b3d4fc",
	Black:               "#2e3436",
	Red:                 "#cc0000",
	Green:               "#4e9a06",
	Yellow:              "#c4a000",
	Blue:                "#3465a4",
	Magenta:             "#75507b",
	Cyan:                "#06989a",
	White:               "#d3d7cf",
	BrightBlack:         "#555753",
	BrightRed:           "#ef2929",
	BrightGreen:         "#8ae234",
	BrightYellow:        "#fce94f",
	BrightBlue:          "#729fcf",
	BrightMagenta:       "#ad7fa8",
	BrightCyan:          "#34e2e2",
	BrightWhite:         "#eeeeec",
}

ThemeUbuntu provides the Ubuntu terminal color scheme

Functions

func Colorize

func Colorize(s string, color string) string

func StripAnsiCodes

func StripAnsiCodes(s string) string

Types

type Handler

type Handler struct {
	CutPrefix string
	Terminal  Terminal
	// contains filtered or unexported fields
}

func (Handler) ServeHTTP

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ITail

type ITail interface {
	Start() error
	Stop() error
	Lines() <-chan string
}

func New

func New(filename string, opts ...Option) ITail

New creates Tail instance

func NewMultiTail

func NewMultiTail(tails ...ITail) ITail

type MultiTail

type MultiTail struct {
	// contains filtered or unexported fields
}

MultiTail allows tailing multiple files and merging their output

func (*MultiTail) Lines

func (mt *MultiTail) Lines() <-chan string

func (*MultiTail) Start

func (mt *MultiTail) Start() error

func (*MultiTail) Stop

func (mt *MultiTail) Stop() error

type Option

type Option func(*Tail)

Option is a functional option for Tail

func WithBufferSize

func WithBufferSize(size int) Option

func WithLabel

func WithLabel(label string) Option

func WithLast

func WithLast(n int) Option

func WithPattern

func WithPattern(patterns ...string) Option

func WithPlugins

func WithPlugins(p ...Plugin) Option

func WithPollInterval

func WithPollInterval(d time.Duration) Option

WithPollInterval sets the polling interval for checking file changes

func WithSyntaxHighlighting

func WithSyntaxHighlighting(syntax ...string) Option

type Pattern

type Pattern []*regexp.Regexp

func (Pattern) Match

func (p Pattern) Match(s string) bool

type Plugin

type Plugin interface {
	// Apply processes a line and returns the modified line
	// and a boolean indicating processing ahead
	// if further plugins should continue processing
	// or drop the line.
	Apply(line string) (string, bool)
}

func NewWithSyntaxHighlighting

func NewWithSyntaxHighlighting(syntax ...string) Plugin

type Tail

type Tail struct {
	// contains filtered or unexported fields
}

Tail provides functionality to tail a file it works similar to 'tail -F' command in unix, which follows the file even if it is rotated

func (*Tail) Lines

func (tail *Tail) Lines() <-chan string

Lines returns output channel caller can read lines from this channel

func (*Tail) Start

func (tail *Tail) Start() error

Start begins tailing the file

func (*Tail) Stop

func (tail *Tail) Stop() error

Stop stops tailing the file

type TailOption

type TailOption struct {
	Filename string   `json:"filename"`
	Options  []Option `json:"options"`
	Alias    string   `json:"alias"`
	Label    string   `json:"label"`
}

type TemplateData

type TemplateData struct {
	Terminal Terminal
	Files    []string
}

func (TemplateData) Localize

func (td TemplateData) Localize(s string) string

type Terminal

type Terminal struct {
	CursorBlink         bool          `json:"cursorBlink"`
	CursorInactiveStyle string        `json:"cursorInactiveStyle,omitempty"`
	CursorStyle         string        `json:"cursorStyle,omitempty"`
	FontSize            int           `json:"fontSize,omitempty"`
	FontFamily          string        `json:"fontFamily,omitempty"`
	Theme               TerminalTheme `json:"theme"`
	Scrollback          int           `json:"scrollback,omitempty"`
	DisableStdin        bool          `json:"disableStdin"`
	ConvertEol          bool          `json:"convertEol,omitempty"`

	Localization map[string]string `json:"-"`
	// contains filtered or unexported fields
}

func DefaultTerminal

func DefaultTerminal() Terminal

func NewTerminal

func NewTerminal(opts ...TerminalOption) Terminal

func (Terminal) Close

func (t Terminal) Close()

Close stops any active watchers associated with the terminal and explicitly stop sse sessions. the http server might be blocked on Shutdown() if there are active watchers.

func (Terminal) Handler

func (to Terminal) Handler(cutPrefix string) Handler

func (Terminal) String

func (tt Terminal) String() string

type TerminalOption

type TerminalOption func(*Terminal)

func WithFontFamily

func WithFontFamily(family string) TerminalOption

func WithFontSize

func WithFontSize(size int) TerminalOption

func WithLocalization

func WithLocalization(localization map[string]string) TerminalOption

func WithScrollback

func WithScrollback(lines int) TerminalOption

func WithTail

func WithTail(filename string, opts ...Option) TerminalOption

func WithTailLabel

func WithTailLabel(label string, filename string, opts ...Option) TerminalOption

func WithTheme

func WithTheme(theme TerminalTheme) TerminalOption

type TerminalTheme

type TerminalTheme struct {
	Background                  string `json:"background,omitempty"`
	Foreground                  string `json:"foreground.omitempty"`
	SelectionBackground         string `json:"selectionBackground,omitempty"`
	SelectionForeground         string `json:"selectionForeground,omitempty"`
	SelectionInactiveBackground string `json:"selectionInactiveBackground,omitempty"`
	Cursor                      string `json:"cursor,omitempty"`
	CursorAccent                string `json:"cursorAccent,omitempty"`
	ExtendedAnsi                string `json:"extendedAnsi,omitempty"`
	Black                       string `json:"black,omitempty"`
	Blue                        string `json:"blue,omitempty"`
	BrightBlack                 string `json:"brightBlack,omitempty"`
	BrightBlue                  string `json:"brightBlue,omitempty"`
	BrightCyan                  string `json:"brightCyan,omitempty"`
	BrightGreen                 string `json:"brightGreen,omitempty"`
	BrightMagenta               string `json:"brightMagenta,omitempty"`
	BrightRed                   string `json:"brightRed,omitempty"`
	BrightWhite                 string `json:"brightWhite,omitempty"`
	BrightYellow                string `json:"brightYellow,omitempty"`
	Cyan                        string `json:"cyan,omitempty"`
	Green                       string `json:"green,omitempty"`
	Magenta                     string `json:"magenta,omitempty"`
	Red                         string `json:"red,omitempty"`
	White                       string `json:"white,omitempty"`
	Yellow                      string `json:"yellow,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL