Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions src/SeqCli/Csv/CsvWriter.cs
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
using System;
using System.Collections.Generic;
using System.IO;
using Seq.Api.Model.Data;
using SeqCli.Mcp.Data;
using Serilog.Sinks.SystemConsole.Themes;
using SeqCli.Output;
using Serilog.Templates.Themes;

namespace SeqCli.Csv;

static class CsvWriter
{
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, ConsoleTheme theme, TextWriter output)
public static void WriteQueryResult(QueryResultPart result, Func<object?, string> stringify, TemplateTheme? theme, TextWriter output)
{
if (!string.IsNullOrWhiteSpace(result.Error))
{
theme.Set(output, ConsoleThemeStyle.Text);
theme?.Set(output, TemplateThemeStyle.Text);
QueryResultHelper.WriteErrorResult(output, result);
theme.Reset(output);
theme?.Reset(output);
}

var first = true;
Expand All@@ -30,47 +32,47 @@ public static void WriteQueryResult(QueryResultPart result, Func<object?, string
});
}

static void WriteCell(TextWriter output, ConsoleTheme theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
static void WriteCell(TextWriter output, TemplateTheme? theme, object? value, Func<object?, string> stringify, ref bool firstCol, bool isHeadingRow = false)
{
if (firstCol)
{
firstCol = false;
}
else
{
theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write(',');
theme.Reset(output);
theme?.Reset(output);
}

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);

var valueAsString = stringify(value);

var dataStyle = isHeadingRow ? ConsoleThemeStyle.Name : ConsoleThemeStyle.Text;
var dataStyle = isHeadingRow ? TemplateThemeStyle.Name : TemplateThemeStyle.Text;
var doubleQuote = valueAsString.IndexOf('"');
while (doubleQuote != -1)
{
theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString[..doubleQuote]);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.Scalar);
theme?.Set(output, TemplateThemeStyle.Scalar);
output.Write("\"\"");
theme.Reset(output);
theme?.Reset(output);

valueAsString = valueAsString[(doubleQuote + 1)..];
doubleQuote = valueAsString.IndexOf('"');
}

theme.Set(output, dataStyle);
theme?.Set(output, dataStyle);
output.Write(valueAsString);
theme.Reset(output);
theme?.Reset(output);

theme.Set(output, ConsoleThemeStyle.TertiaryText);
theme?.Set(output, TemplateThemeStyle.TertiaryText);
output.Write('"');
theme.Reset(output);
theme?.Reset(output);
}
}
6 changes: 3 additions & 3 deletions src/SeqCli/Forwarder/ForwarderModule.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,13 +68,13 @@ protected override void Load(ContainerBuilder builder)
Log.ForContext<ForwarderModule>().Warning("Configured to expose ingestion log via HTTP API");
builder.RegisterType<IngestionLogEndpoints>().As<IMapEndpoints>();

var ingestionLogTemplate = "[{@t:o} {@l:u3}] {@m}\n";
var ingestionLogTemplate = $"[{{@t:o}} {{@l:u3}}] {{@m}}{Environment.NewLine}";
if (_config.Forwarder.Diagnostics.IngestionLogShowDetail)
{
Log.ForContext<ForwarderModule>().Warning("Including full client, payload, and error detail in the ingestion log");
ingestionLogTemplate +=
"{#if ClientHostIP is not null}Client IP address: {ClientHostIP}\n{#end}" +
"{#if DocumentStart is not null}First {StartToLog} characters of payload: {DocumentStart:l}\n{#end}" +
$"{{#if ClientHostIP is not null}}Client IP address: {{ClientHostIP}}{Environment.NewLine}{{#end}}" +
$"{{#if DocumentStart is not null}}First {{StartToLog}} characters of payload: {{DocumentStart:l}}{Environment.NewLine}{{#end}}" +
"{@x}";
}

Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Ingestion/LogShipper.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ namespace SeqCli.Ingestion;

static class LogShipper
{
static readonly ITextFormatter JsonFormatter = OutputFormatter.Json(null);
static readonly ITextFormatter JsonFormatter = TextFormatters.Json(null);

public static async Task ShipBufferAsync(
SeqConnection connection,
Expand Down
6 changes: 3 additions & 3 deletions src/SeqCli/Mcp/McpServerInstaller.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,13 +87,13 @@ static class McpServerInstaller
"mcpServers"),

["codex"] = Unsupported(
"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:\n\n[mcp_servers.seq]\ncommand = \"seqcli\"\nargs = [\"mcp\", \"run\"]"),
$"Codex reads MCP servers from ~/.codex/config.toml (TOML), which seqcli can't edit automatically. Add this block:{Environment.NewLine}{Environment.NewLine}[mcp_servers.seq]{Environment.NewLine}command = \"seqcli\"{Environment.NewLine}args = [\"mcp\", \"run\"]"),

["goose"] = Unsupported(
"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:\n\nextensions:\n seq:\n type: stdio\n cmd: seqcli\n args: [mcp, run]\n enabled: true"),
$"Goose reads MCP servers from ~/.config/goose/config.yaml (YAML) under `extensions`, which seqcli can't edit automatically. Add:{Environment.NewLine}{Environment.NewLine}extensions:{Environment.NewLine} seq:{Environment.NewLine} type: stdio{Environment.NewLine} cmd: seqcli{Environment.NewLine} args: [mcp, run]{Environment.NewLine} enabled: true"),

["continue"] = Unsupported(
"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:\n\nname: Seq\nversion: 0.0.1\nschema: v1\nmcpServers:\n - name: seq\n command: seqcli\n args:\n - mcp\n - run"),
$"Continue reads MCP servers from YAML, which seqcli can't edit automatically. Create .continue/mcpServers/seq.yaml with:{Environment.NewLine}{Environment.NewLine}name: Seq{Environment.NewLine}version: 0.0.1{Environment.NewLine}schema: v1{Environment.NewLine}mcpServers:{Environment.NewLine} - name: seq{Environment.NewLine} command: seqcli{Environment.NewLine} args:{Environment.NewLine} - mcp{Environment.NewLine} - run"),
};

static readonly IReadOnlyDictionary<string, string> AgentAliases =
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Mcp/Tools/Search/SearchTools.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,7 +43,7 @@ class SearchTools(McpSession session, SeqConnection connection)
{
const string ResultIdPropertyName = "__seqcli_ResultId";
static readonly ExpressionTemplate SearchResultFormatter = new (
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}\n{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...\n{{#end}}"
$"{{{ResultIdPropertyName}}} [{{UtcDateTime(@t)}} {{{LevelMapping.SurrogateLevelProperty}}}] {{@m}}{Environment.NewLine}{{#if @x is not null}}{{Substring(ToString(@x), 0, 512)}}...{Environment.NewLine}{{#end}}"
);

[McpServerTool(Name = "seq_new_session", ReadOnly = true, Title = "Begin a new Search/Query Session")]
Expand Down
70 changes: 70 additions & 0 deletions src/SeqCli/Output/FlareTheme.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
// Copyright © Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Collections.Generic;
using System.IO;
using Serilog.Templates.Themes;

namespace SeqCli.Output;

/// <summary>
/// <c>Flare</c> is Seq's embedded stream/columnar database. This theme is derived from one build originally
/// for the <c>flaretl</c> command-line tooling used there.
/// </summary>
static class FlareTheme
{
static readonly Dictionary<TemplateThemeStyle, string> FlareThemeStyles = new()
{
[TemplateThemeStyle.Name] = "\e[38;5;0215m",
[TemplateThemeStyle.Number] = "\e[38;5;0200m",
[TemplateThemeStyle.Boolean] = "\e[38;5;0039m",
[TemplateThemeStyle.Null] = "\e[38;5;0039m",
[TemplateThemeStyle.String] = "\e[38;5;0217m",
[TemplateThemeStyle.Scalar] = "\e[38;5;0217m",
[TemplateThemeStyle.LevelError] = "\e[38;5;0197m",
[TemplateThemeStyle.TertiaryText] = "\e[38;5;0244m",
// Based on `TemplateTheme.Code`
[TemplateThemeStyle.Text] = "\e[38;5;0253m",
[TemplateThemeStyle.SecondaryText] = "\e[38;5;0246m",
[TemplateThemeStyle.Invalid] = "\e[33;1m",
[TemplateThemeStyle.LevelVerbose] = "\e[37m",
[TemplateThemeStyle.LevelDebug] = "\e[37m",
[TemplateThemeStyle.LevelInformation] = "\e[37;1m",
[TemplateThemeStyle.LevelWarning] = "\e[38;5;0229m",
[TemplateThemeStyle.LevelFatal] = "\e[38;5;0197m\e[48;5;0238m"
};

public static readonly TemplateTheme SeqCli = new(FlareThemeStyles);

// `CsvWriter` implements its own theming behavior because the required APIs are not public in Serilog.Expressions.
// The best way forward for this is likely to be porting theming to Seq.Syntax, and exposing the required APIs there.

const string AnsiStyleResetSequence = "\e[0m";

// The passed-in theme is ignored because SerilogExpressions themes are opaque. All formatting uses the SeqCli theme.
// ReSharper disable once UnusedParameter.Global
extension(TemplateTheme theme)
{
public void Set(TextWriter output, TemplateThemeStyle style)
{
if (FlareThemeStyles.TryGetValue(style, out var styleSequence))
output.Write(styleSequence);
}

public void Reset(TextWriter output)
{
output.Write(AnsiStyleResetSequence);
}
}
}
85 changes: 26 additions & 59 deletions src/SeqCli/Output/OutputFormat.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,7 +32,6 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog.Templates.Themes;

namespace SeqCli.Output;
Expand All@@ -41,21 +40,9 @@ sealed class OutputFormat
{
// See https://no-color.org for semantics.
const string NoColorEnvironmentVariable = "NO_COLOR";

internal const string DefaultOutputTemplate =
"[{Timestamp:o} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

static bool AnsiIsDefault => !OperatingSystem.IsWindows();

internal static readonly ConsoleTheme DefaultAnsiTheme = AnsiConsoleTheme.Code;

internal static readonly ConsoleTheme DefaultTheme =
AnsiIsDefault ? DefaultAnsiTheme : SystemConsoleTheme.Literate;

static readonly TemplateTheme DefaultTemplateTheme = TemplateTheme.Code;


readonly OutputSyntax _syntax;
readonly string _outputTemplate;
readonly string? _outputTemplate;
readonly Logger _formatter;

readonly JsonSerializer _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
Expand All@@ -80,7 +67,8 @@ public OutputFormat(
outputConfig,
outputTemplate,
noColorSetInEnvironment: NoColorSetInEnvironment(),
outputIsRedirected: Console.IsOutputRedirected)
outputIsRedirected: Console.IsOutputRedirected,
allowAnsiEscapes: TerminalFeatures.TryEnableAnsiEscapes())
{
}

Expand All@@ -91,51 +79,45 @@ public OutputFormat(
/// <param name="outputTemplate">The template controlling plain-text formatting, or <c>null</c> for the default.</param>
/// <param name="noColorSetInEnvironment">Whether <c>NO_COLOR</c> is set; see <see cref="NoColorSetInEnvironment"/>.</param>
/// <param name="outputIsRedirected">Whether <c>STDOUT</c> is redirected, i.e. not attached to a terminal.</param>
/// <param name="allowAnsiEscapes">Whether ANSI escape sequences are allowed; generally <c>false</c> for interactive
/// legacy Windows terminals and <c>true</c> otherwise.</param>
internal OutputFormat(
OutputSyntax syntax,
bool? noColor,
bool? forceColor,
SeqCliOutputConfig outputConfig,
string? outputTemplate,
bool noColorSetInEnvironment,
bool outputIsRedirected)
bool outputIsRedirected,
bool allowAnsiEscapes)
{
_syntax = syntax;
_outputTemplate = outputTemplate ?? DefaultOutputTemplate;

NoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment);
ApplyThemeToRedirectedOutput = !NoColor && (forceColor ?? outputConfig.ForceColor);

// Serilog's console sink applies the `NO_COLOR` convention itself, unconditionally, overriding whatever
// theme it's passed. When `--force-color` has opted back out of `NO_COLOR`, the variable is cleared (for
// this process only) so that the sink can't undo the decision made here.
if (!NoColor && noColorSetInEnvironment)
Environment.SetEnvironmentVariable(NoColorEnvironmentVariable, null);
_outputTemplate = outputTemplate;

var colorize = !NoColor && (ApplyThemeToRedirectedOutput || !outputIsRedirected);
var resolvedNoColor = ResolveNoColor(noColor, forceColor, outputConfig, noColorSetInEnvironment, allowAnsiEscapes);
var applyThemeToRedirectedOutput = !resolvedNoColor && (forceColor ?? outputConfig.ForceColor);
var colorize = !resolvedNoColor && (applyThemeToRedirectedOutput || !outputIsRedirected);

Theme = !colorize ? ConsoleTheme.None
: ApplyThemeToRedirectedOutput ? DefaultAnsiTheme
: DefaultTheme;

// Rather than emit escapes that a downlevel Windows terminal would show literally,
// JSON output stays plain there unless ANSI has been opted into with `--force-color`.
TemplateTheme = colorize && (ApplyThemeToRedirectedOutput || AnsiIsDefault)
? DefaultTemplateTheme
TemplateTheme = colorize
? FlareTheme.SeqCli
: null;

_formatter = CreateOutputLogger();
}

static bool NoColorSetInEnvironment()
=> !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(NoColorEnvironmentVariable));

static bool ResolveNoColor(
internal static bool ResolveNoColor(
bool? noColorFlag,
bool? forceColorFlag,
SeqCliOutputConfig config,
bool noColorSetInEnvironment)
bool noColorSetInEnvironment,
bool supportsAnsiEscapes)
{
if (!supportsAnsiEscapes)
return true;

if (noColorFlag != null)
return noColorFlag.Value;

Expand All@@ -149,12 +131,6 @@ static bool ResolveNoColor(
public bool Text => _syntax == OutputSyntax.Text;
public bool Native => _syntax == OutputSyntax.Native;

internal bool NoColor { get; }

bool ApplyThemeToRedirectedOutput { get; }

internal ConsoleTheme Theme { get; }

internal TemplateTheme? TemplateTheme { get; }

public bool RequiresRender => Native;
Expand All@@ -167,14 +143,11 @@ Logger CreateOutputLogger()

if (Json)
{
outputConfiguration.WriteTo.Console(OutputFormatter.Json(TemplateTheme));
outputConfiguration.WriteTo.Console(TextFormatters.Json(TemplateTheme));
}
else if (Text)
{
outputConfiguration.WriteTo.Console(
outputTemplate: _outputTemplate,
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput);
outputConfiguration.WriteTo.Console(TextFormatters.Plain(TemplateTheme, _outputTemplate));
}

// The logger is not configured for Native output, which avoids it. Ideally we'll shift away from using
Expand All@@ -198,10 +171,7 @@ public void WriteEntity(Entity entity)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -231,10 +201,7 @@ public void WriteObject(object value)
var writer = new LoggerConfiguration()
.Destructure.With<JsonNetDestructuringPolicy>()
.Enrich.With<StripStructureTypeEnricher>()
.WriteTo.Console(
outputTemplate: "{@Message:j}{NewLine}",
theme: Theme,
applyThemeToRedirectedOutput: ApplyThemeToRedirectedOutput)
.WriteTo.Console(TextFormatters.Plain(TemplateTheme, "{@m}" + Environment.NewLine))
.CreateLogger();
writer.Information("{@Entity}", jo);
}
Expand DownExpand Up@@ -277,7 +244,7 @@ public void WriteQueryResult(QueryResultPart result)
}
else
{
CsvWriter.WriteQueryResult(result, Stringify, Theme, Console.Out);
CsvWriter.WriteQueryResult(result, Stringify, TemplateTheme, Console.Out);
}
}

Expand Down
Loading