Skip to content

Diagnostics, logging and strict mode

Problems inside a document never stop a render: a missing image, an invalid CSS declaration or a character no font has is reported as a diagnostic and the PDF is written anyway. Every result carries the diagnostics of its call. A document that uses only supported, valid HTML and CSS, whose resources all load and whose glyphs all exist, has none.

The diagnostic

Field Meaning
severity error, warning or info
code a stable identifier, for example resource.not-found or css.invalid-value
message a text for people; its wording may change between versions
url the resource the diagnostic is about, when there is one
location where the cause is: the source (document or stylesheet URL), line and column, both counted from 1

Match on code, severity, url and the location, never on the message. In an HTML source the location is the < of the element's start tag; in CSS it is the start of the declaration, the rule's selector or the at-rule. CSS inside a <style> element is located in the HTML source.

The diagnostics of a call are sorted by phase (loading and parsing, then layout, then writing), then by source in the order the sources were loaded, then by line and column. A diagnostic with the same code, URL and location as an earlier one is not repeated. Every code is listed in the diagnostic codes reference.

On the command line

The command line prints the diagnostics on standard error, one line each:

kolinsky render broken.html -o broken.pdf --diagnostics json

prints, with --diagnostics json, one JSON object per line (paths shortened here):

{"severity":"warning","code":"resource.not-found","message":"the stylesheet missing.css could not be loaded","url":"file:///work/missing.css","source":"file:///work/broken.html","line":6,"column":1}
{"severity":"warning","code":"resource.not-found","message":"cannot load file:///work/missing.png: No such file or directory (os error 2)","url":"file:///work/missing.png","source":"file:///work/broken.html","line":10,"column":3}

and without it (--diagnostics human, the default):

warning: resource.not-found: the stylesheet missing.css could not be loaded (file:///work/broken.html:6:1)
warning: resource.not-found: cannot load file:///work/missing.png: No such file or directory (os error 2) (file:///work/broken.html:10:3)

Errors and warnings are printed by default. -v (--verbose) adds the info diagnostics (for example overflow.page, content that extends beyond the page) and progress lines; -q (--quiet) prints only errors. When a run fails for another reason, a last line names the failure (error: ..., or in JSON an object with the code error.fetch, error.parse, error.pdf or error.io).

The exit status:

Status Meaning
0 the PDF was written (warnings may have been printed)
1 an error: a usage error, an input or user stylesheet that cannot be loaded, an invalid option value, a PDF that cannot be written
2 strict mode failed the run; nothing was written

In Rust

Rendered::diagnostics holds the list of a successful call; print or collect them as your application needs.

In Python

Result.diagnostics and Document.diagnostics hold the list as frozen kolinsky.Diagnostic objects, with the fields severity, code, message, url, source, line, column and the property category. Each diagnostic is also logged on the logger kolinsky at ERROR, WARNING or INFO, with the message "<code>: <message>" and the diagnostic as the record attribute diagnostic. The module adds only a NullHandler, so nothing is printed until your application configures logging.

import logging
from pathlib import Path

import kolinsky

# Diagnostics are logged on the "kolinsky" logger; nothing is printed until logging is configured
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")

result = kolinsky.render(Path("broken.html"))
for d in result.diagnostics:
    print(d.severity, d.code, d.url, d.line, d.column, d.category)
Path("broken.pdf").write_bytes(result.pdf)

try:
    kolinsky.render(Path("broken.html"), options=kolinsky.Options(strict=("missing-resources",)))
except kolinsky.KolinskyStrictError as e:
    print(f"{len(e.diagnostics)} diagnostics, the first: {e.diagnostics[0].code}")

Strict mode

Strict mode turns the diagnostics of chosen categories into errors, for pipelines where a PDF with a missing image or font is worse than no PDF:

Category Codes
missing-resources resource.*
missing-glyphs glyph.missing
tags tags.* (tagged PDF, PDF/UA)
overflow overflow.page

With strict set, a call that finds a diagnostic of one of the categories fails: each such diagnostic gets the severity error, and the call returns the strict error with the whole list of the call instead of the result. The layout fails for missing resources, missing glyphs and overflow, writing the PDF for tags; nothing is written. Diagnostics of other categories keep their severity, and diagnostics without a category (css.*, html.*, link.*, pdf.*) never fail a call.

  • Command line: --strict for all four categories, --strict=missing-resources,missing-glyphs for some.
  • Python: Options(strict=True) or Options(strict=("missing-resources",)); the error is kolinsky.KolinskyStrictError with the list in diagnostics.
  • Rust: RenderOptions::strict with StrictFlags (StrictFlags::ALL, or a union such as StrictFlags::MISSING_RESOURCES | StrictFlags::TAGS); the error is Error::Strict(list).
use kolinsky::{Engine, Error, Input, PdfOptions, RenderOptions, Severity, StrictFlags};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let engine = Engine::new();

    // By default problems inside the document are diagnostics, and the PDF is written
    let rendered = engine.render(Input::Path("broken.html".into()), &RenderOptions::default(), &PdfOptions::default())?;
    for d in &rendered.diagnostics {
        let at = d.location.as_ref().map(|l| format!(" (line {}, column {})", l.line, l.column)).unwrap_or_default();
        eprintln!("{}: {}: {}{at}", d.severity.name(), d.code, d.message);
    }
    std::fs::write("broken.pdf", rendered.output)?;

    // In strict mode a missing resource fails the call and nothing is written
    let mut strict = RenderOptions::default();
    strict.strict = StrictFlags::MISSING_RESOURCES | StrictFlags::MISSING_GLYPHS;
    match engine.render(Input::Path("broken.html".into()), &strict, &PdfOptions::default()) {
        Err(Error::Strict(list)) => {
            let errors: Vec<_> = list.iter().filter(|d| d.severity == Severity::Error).collect();
            eprintln!("{} diagnostics failed the render", errors.len());
        }
        Ok(_) => unreachable!("broken.html has missing resources"),
        Err(other) => return Err(other.into()),
    }
    Ok(())
}

Errors

A call fails only for reasons outside the document:

Rust Python When
Error::Fetch KolinskyFetchError the input, a user stylesheet or an attachment file cannot be loaded
Error::Parse KolinskyParseError (also a ValueError) an option value does not parse: page size, margin, URL pattern, page range, strict categories, standards; an invalid query selector; font data that is not a font
Error::Strict KolinskyStrictError strict mode
Error::Pdf KolinskyPdfError the PDF cannot be produced: no page selected, a-2b with attachments, the output cannot be written

All Python errors derive from kolinsky.KolinskyError, which has the diagnostics of the failed call in diagnostics.