by

Awesome Asciidoctor.js: Catch processing errors and warnings using an in-memory logger

The new logging system introduces in Asciidoctor.js, can be used to catch processing errors and warnings. It can be really useful in a CI build when you want to make sure that your documentation is perfect before publishing it.

The in-memory logger stores every warning and error messages generated by the Asciidoctor.js processor. Once the processing is done, you can retrieve all these messages using the getMessages function:

const asciidoctor = require('asciidoctor.js')()
const loggerManager = asciidoctor.LoggerManager
const memoryLogger = asciidoctor.MemoryLogger.$new()
loggerManager.setLogger(memoryLogger)

asciidoctor.convert('input')

memoryLogger.getMessages() // returns an array of Message

For every message, you can get the following information:

const message = memoryLogger.getMessages()[0]
console.log(message.getSeverity()) 
console.log(message.getText()) 
const sourceLocation = message.getSourceLocation() 
if (sourceLocation) {
  console.log(sourceLocation.getLineNumber()) 
  console.log(sourceLocation.getFile()) 
  console.log(sourceLocation.getDirectory()) 
  console.log(sourceLocation.getPath()) 
}
1 returns the severity (ERROR or WARNING)
2 returns the error or warning text message
3 returns the context about the source location (can be undefined)
4 returns the source line number associated to the message
5 returns the file name associated to the message (or undefined when converting from a String)
6 returns the absolute path to the source file parent directory, or the execution path when converting from a String
7 returns the path associated to the message (or <stdin> when converting from a String)

You could then check if there’s any error and fail your CI build using process.exit() function:

const messages = memoryLogger.getMessages()
const errors = messages.filter(message => message.getSeverity() === 'ERROR')
if (errors && errors.length > 0) {
  console.log(`${errors.length} errors thrown during the documentation generation, exiting.`)
  process.exit(1)
} else {
  // all good, continuing...
}

Written with Asciidoctor.js 1.5.9.