feat: add opt-in LSP lifecycle logs

This commit is contained in:
Dandaedre 2026-09-29 17:07:05 +02:00
parent 5e99a59f8d
commit 883fb13c12
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
4 changed files with 47 additions and 3 deletions

View File

@ -26,6 +26,10 @@ struct Cli {
/// Load an explicit TOML configuration after user configuration.
#[arg(long, value_name = "FILE")]
config: Option<PathBuf>,
/// Emit newline-delimited JSON lifecycle logs to standard error.
#[arg(long)]
log_json: bool,
}
#[tokio::main]
@ -33,7 +37,9 @@ async fn main() -> Result<()> {
let cli = Cli::parse();
let loader = ConfigLoader::discover(cli.config_name.as_ref(), cli.config)?;
let config = loader.load()?;
let (service, socket) = LspService::new(|client| LspBackend::new(client, loader, config));
let (service, socket) = LspService::new(|client| {
LspBackend::new(client, loader, config).with_json_logging(cli.log_json)
});
Server::new(tokio::io::stdin(), tokio::io::stdout(), socket)
.serve(service)
.await;

View File

@ -270,6 +270,7 @@ pub struct LspBackend {
config_loader: ConfigLoader,
config: RwLock<Config>,
documents: RwLock<DocumentStore>,
log_json: bool,
}
impl LspBackend {
@ -280,9 +281,35 @@ impl LspBackend {
config_loader,
config: RwLock::new(config),
documents: RwLock::new(DocumentStore::default()),
log_json: false,
}
}
/// Enable newline-delimited JSON lifecycle logging on standard error.
#[must_use]
pub const fn with_json_logging(mut self, enabled: bool) -> Self {
self.log_json = enabled;
self
}
fn log(&self, level: &str, event: &str, uri: Option<&Uri>, version: Option<i32>) {
if !self.log_json {
return;
}
let mut record = serde_json::json!({
"component": "john-slop-lsp",
"event": event,
"level": level,
});
if let Some(uri) = uri {
record["uri"] = serde_json::Value::String(uri.as_str().to_owned());
}
if let Some(version) = version {
record["version"] = serde_json::Value::from(version);
}
eprintln!("{record}");
}
async fn publish_replacements(&self, uri: Uri) {
let Some(snapshot) = self.documents.read().await.get(&uri) else {
return;
@ -329,21 +356,28 @@ impl LanguageServer for LspBackend {
})
}
async fn initialized(&self, _: InitializedParams) {}
async fn initialized(&self, _: InitializedParams) {
self.log("info", "initialized", None, None);
}
async fn shutdown(&self) -> JsonResult<()> {
self.log("info", "shutdown", None, None);
Ok(())
}
async fn did_open(&self, params: DidOpenTextDocumentParams) {
let uri = params.text_document.uri.clone();
let version = params.text_document.version;
self.documents.write().await.open(params);
self.log("info", "document-opened", Some(&uri), Some(version));
self.publish_replacements(uri).await;
}
async fn did_change(&self, params: DidChangeTextDocumentParams) {
let uri = params.text_document.uri.clone();
let version = params.text_document.version;
if self.documents.write().await.change(params) {
self.log("info", "document-changed", Some(&uri), Some(version));
self.publish_replacements(uri).await;
}
}
@ -351,6 +385,7 @@ impl LanguageServer for LspBackend {
async fn did_close(&self, params: DidCloseTextDocumentParams) {
let uri = params.text_document.uri;
self.documents.write().await.close(&uri);
self.log("info", "document-closed", Some(&uri), None);
self.client.publish_diagnostics(uri, Vec::new(), None).await;
}
@ -358,6 +393,7 @@ impl LanguageServer for LspBackend {
let config = match self.config_loader.load() {
Ok(config) => config,
Err(error) => {
self.log("error", "configuration-reload-failed", None, None);
self.client
.show_message(
MessageType::ERROR,
@ -368,6 +404,7 @@ impl LanguageServer for LspBackend {
}
};
*self.config.write().await = config;
self.log("info", "configuration-reloaded", None, None);
let uris = self.documents.read().await.uris();
for uri in uris {
self.publish_replacements(uri).await;

View File

@ -201,7 +201,7 @@ first formatter milestone tag.
replacement engine; reject stale-version requests.
- [x] Recompute after open/change/configuration updates, clear on close, and avoid
publishing obsolete results when analysis overlaps newer edits.
- [ ] Keep all protocol bytes on stdout and diagnostics/logging on stderr. Add
- [x] Keep all protocol bytes on stdout and diagnostics/logging on stderr. Add
opt-in structured logging without document contents.
- [ ] Add in-process protocol tests for lifecycle, versions, Unicode positions,
config reload, close cleanup, invalid URI, malformed messages, concurrent

View File

@ -28,6 +28,7 @@ fn lsp_help_contains_helix_and_vim_setup() {
assert!(output.stderr.is_empty());
assert!(stdout.contains("[language-server.john-slop]"));
assert!(stdout.contains("command = \"john-slop-lsp\""));
assert!(stdout.contains("--log-json"));
assert!(stdout.contains("lsp#register_server"));
assert!(stdout.contains("['john-slop-lsp']"));
}