seqcli

repository·dev·Indexed 41 days ago

https://github.com/datalust/seqcli

The Seq command-line client for administering, logging, ingesting, and searching Seq from any OS. It provides a comprehensive interface for managing alerts, API keys, .NET [SeqApp] plug-ins, and server settings, and includes support for AI agents via skills and the Model Context Protocol (MCP).

Tokens
75.5K
Snippets
278
Records
319
Agent score
50%

What's inside seqcli

  1. Use SeqCli.Templates for importing related entities

    dev
    SeqCli.Templates is a JSON-based templating system designed to facilitate the import of sets of related entities into a Seq server. It uses a JSON superset syntax that allows for JavaScript-style function calls to resolve relationships between entities during the import process.
  2. Use Seq.Syntax for customizable app templates

    dev

    Apps that support user-customizable output should use the Seq.Syntax template language. Templates are compiled into ExpressionTemplate instances and rendered against a LogEvent.

    Template Compilation

    Compile templates in OnAttached() or a factory constructor using an OrderedNameResolver to provide access to built-in functions and custom app properties.

    Custom Encoding

    If your output format requires escaping (like HTML), implement TemplateOutputEncoder. Note that the encoder is applied only to interpolated values, not to the literal template text.

    Built-in Functions and Name Resolution

    You can expose custom functions and properties (like @Host or @App) to templates by implementing a NameResolver that maps these tokens to your app's instances.

    // Template compilation
    using Seq.Syntax.Templates;
    using Seq.Syntax.Templates.Encoding;
    
    var template = new ExpressionTemplate(
        templateText,
        nameResolver: new OrderedNameResolver(new NameResolver[]
        {
            new StaticMemberNameResolver(typeof(MyBuiltInFunctions)),
            myAppNameResolver
        }),
        encoder: isPlainText ? null : new MyHtmlEncoder());
    
    // Template rendering
    static string Format(ExpressionTemplate template, LogEvent evt)
    {
        var writer = new StringWriter();
        template.Format(evt, writer);
        return writer.ToString();
    }
    
    // Custom encoding
    class TemplateOutputTelegramHtmlEncoder : TemplateOutputEncoder
    {
        public override string Encode(string value)
        {
            return value
                .Replace("&", "&")
                .Replace("<", "&lt;")
                .Replace(">", "&gt;");
        }
    }
  3. Template syntax for SeqCli.Templates

    dev

    The templating language is a superset of JSON. It allows you to use JavaScript-style function calls within JSON values to dynamically resolve data. This is particularly useful for linking entities (like signals or users) that are being imported in the same batch.

    Supported functions:

    • ref(filename): Resolves to the unique ID of the entity produced by importing the specified filename into the target Seq instance. This allows you to create references to other entities defined within your template set.
    {
        "Title": "Web",
        "SignalId": ref("signal-HTTP Requests.json")
    }
  4. Use the store-and-forward ingestion proxy

    dev

    The seqcli forwarder commands provide a durable ingestion buffer for systems with intermittent connectivity. The forwarder implements the Seq ingestion API, allowing applications to write directly to the forwarder, which persists data locally until it can be successfully sent to the destination Seq server.

    Security Note: The forwarder HTTP API does not authenticate incoming requests by default. It is designed for local use in isolated environments (e.g., firewalled machines or secured container networks). If you enable additional APIs like the ingestion log, ensure they are not reachable externally.

    # Start a forwarder listening on port 5341 and forwarding to a remote Seq server
    seqcli forwarder run --listen http://127.0.0.1:5341 -s https://seq.example.com
  5. How routing and controllers function in the simulation

    dev

    The Router is the final stage of the middleware chain. It inspects the HttpRequest path and dispatches it to the appropriate action method on a Controller subclass.

    Routing Details:

    • Route Templates: Supports a simple {id} wildcard substitution. Note that the {id} value is not currently extracted or passed to the controller after selection.
    • Log Context: The router pushes Controller and Action properties onto the log context to provide traceability for downstream operations (like database calls).
    • Action Methods: Must be decorated with the [Route] attribute, be asynchronous, accept an HttpRequest, and return an HttpResponse.
  6. Workflow for querying Seq metrics

    dev

    Seq stores OpenTelemetry metric samples in the series data source (a columnar store). To query metrics correctly and avoid performance issues or inaccurate data, you must follow this strict workflow:

    1. Search for metric definitions: Use dedicated tools to find metric names and descriptions.
    2. Identify the metric kind: Determine if the metric is a Sum, Gauge, Fixed, or Exponential type.
    3. List dimensions: Use seqcli metrics dimensions to find which dimensions apply to the metric.
    4. List dimension values (Optional): Use seqcli metrics dimensionvalues to find specific values (e.g., service names) within those dimensions.
    5. Run aggregate queries: Execute queries against the series data source using the discovered names, kinds, and dimensions.

    Critical Constraints

    • NEVER query the series data source directly for metric definitions or available dimensions.
    • NEVER use distinct to list dimension values; use the dedicated dimension value tools instead.
    • NEVER evaluate projection queries against the series data source, as this impacts Seq performance.
    • ALWAYS include where Has(<metric name>) in aggregate queries to avoid row count skew.
  7. How metrics are collected and emitted in Roastery

    dev

    Metrics in this simulation do not use standard .NET System.Diagnostics or OpenTelemetry. Instead, they use plain dictionaries keyed by record structs, allowing for high-cardinality attributes (like RoastId) without pre-registration.

    Metric Types and Behavior:

    • Counters and Histograms: Use delta temporality. Samples accumulate in a Sample instance, which is atomically swapped every five seconds and converted into Metrics sampled log events.
    • Gauges: Represent instantaneous last-write-wins values within a sampling interval.

    Infrastructure:

    • RoasteryMetrics<TSample>: The base class providing collection infrastructure.
    • RoasteryMetricsSample: Converts samples into log events.
    • RoasteryWebMetrics: Handles web frontend metrics (e.g., HTTP durations, order counters).
    • RoasteryProductionMetrics: Handles roasting and ambient environment metrics.
  8. Understand the Seq Event Data Model

    dev

    All events in Seq follow a unified data model. Spans are specifically identified by the presence of the @Start property.

    Built-in Properties

    PropertyTypeDescription
    @ArrivednumberArrival order relative to other events in the same batch.
    @DataobjectCompact internal representation. Avoid using this due to high runtime cost.
    @Elapsednumber?Duration of a span (in 100ns ticks). Only present on spans.
    @EventTypenumberNumeric hash of the @MessageTemplate.
    @Exceptionstring?The exception string (type, message, stack trace).
    @IdstringUnique event ID.
    @LevelstringSeverity (e.g., 'Error', 'ERROR') or span completion status.
    @MessagestringHuman-readable text or the span name.
    @MessageTemplatestringThe message template (messagetemplates.org syntax).
    @ParentIdstring?The @SpanId of the parent span. Only on spans.
    @Propertiesobject?User-defined properties. C-style identifiers (e.g., RequestPath) can be accessed implicitly without the @Properties prefix.
    @Resourceobject?OpenTelemetry resource properties.
    @Scopeobject?OpenTelemetry scope properties.
    @SpanIdstring?W3C span ID. Log events within a span share this value.
    @SpanKindstring?OpenTelemetry span kind. Only on spans.
    @Startnumber?The time the span started.
    @TimestampnumberThe time the event was recorded.
    @TraceIdstring?W3C trace ID. All spans/logs in a trace share this.

    seqcli Usage Tip

    When using seqcli:

    • Use --native to show results in a round-trippable, agent-friendly syntax.
    • Use --json for programmatic use, but note that built-in property names are abbreviated in JSON mode.
  9. Override configuration with environment variables

    dev

    Every setting in seqcli can be overridden at runtime using environment variables. The format is SEQCLI_<setting path>, where the dotted segments of the setting name are replaced by underscores.

    Example: To override the connection.serverUrl setting, use the environment variable SEQCLI_CONNECTION_SERVERURL.

  10. Understand the Seq Type System

    dev

    Seq uses a dynamic type system for stored data and expression evaluation. Seq does not perform type coercion. If a function or operator receives invalid arguments, the result is undefined (similar to NULL in SQL).

    Supported Types

    TypeDescriptionExample Literals
    nullThe atom null.null
    booleanThe atoms true and false.true, false
    numberDecimal numbers (matching .NET decimal precision).0, 12.34, 56ms, DateTime('2026-05-29T10:56:01.43278Z'), 0xa1b234ff
    arrayAn ordered array of values.[], [17, null, {a: 'test'}]
    objectAn unordered set of name/value pairs.{}, {a: 'test', 'b c': 17, d: []}
    anyAn alias for null | boolean | number | array | object.-

    Note: A type followed by ? (e.g., number?) indicates the value may be undefined.

  11. Understand the Roastery simulation architecture

    dev

    The Roastery project is a simulation of a coffee bean ordering web application. It models a full HTTP stack using an in-memory data structure that flows from a client through middleware and routing to server-side controllers.

    The request flow is: HttpClient $\rightarrow$ Middleware $\rightarrow$ Router $\rightarrow$ Controller.

    Key components include:

    • HttpClient: A thin wrapper and factory for HttpRequests that acts as a mock web browser.
    • HttpServer: The base interface for the middleware and routing layer. It defines the InvokeAsync method.
    • Database: A thread-safe in-memory dictionary managing entities like Product and Order.
    • Actors: Concurrent entities (e.g., Customer, WarehouseStaff) that drive the simulation by sending requests via the HttpClient.
    // The core interface for the HTTP pipeline
    abstract class HttpServer
    {
        public abstract Task<HttpResponse> InvokeAsync(HttpRequest request);
    }