bx-orm: Observability
BoxLang is the AI-native software productivity platform for building, modernizing and running applications, with developers and AI agents working together.
bx-orm announces events for SQL, flushes and failures through BoxLang's
interceptor service. Use them to build debuggers, monitors and slow query logs
without reaching into Hibernate.
There is no cost when nothing listens: JDBC objects are only wrapped when a
listener exists as a connection is acquired, and payloads are built lazily.
Events
| Event |
Fires |
Payload |
onORMQuery |
After each JDBC statement. Selects fire when the result set closes, once the row count is known |
sql, kind, elapsedNanos, rows, datasource, appName, hql, entityName, error, params |
onORMFlush |
After each session flush |
inserts, updates, deletes, elapsedNanos, datasource, appName |
onORMException |
When a statement fails |
error, sql, datasource, appName |
onORMQuery payload
| Key |
Description |
sql |
SQL text sent to the driver |
kind |
select, insert, update, delete, ddl or other |
elapsedNanos |
Execution time in nanoseconds (excludes reading rows) |
rows |
Rows returned (select), rows affected (DML), -1 when unknown (DDL) |
datasource |
Datasource name |
appName |
Unique ORM application name |
hql |
HQL behind the statement when it came from ormExecuteQuery(), else null |
entityName |
Entity being loaded when it came from entityLoad() or entityLoadByPK(), else null |
error |
The Throwable if the statement failed, else null |
params |
Ordered array of bound values. Only present when announceQueryParams=true |
A failed statement fires onORMQuery with error set and onORMException.
That includes SQL rejected when the statement is prepared. Startup DDL (for
example dbcreate="dropcreate") is announced too when the listener registers
before the application starts.
onORMFlush counts are statements run during the flush, not entities, so JDBC
batching can make them differ from the number of entities changed.
Other interception points
| Point |
When |
Payload |
ORMPreConfigLoad |
Before bx-orm reads an application's ormSettings |
properties, context |
ORMPostConfigLoad |
After bx-orm reads an application's ormSettings |
properties, context |
post_new |
When entityNew() creates an entity |
entityName, entity, context |
beforeCriteriaBuilderList / afterCriteriaBuilderList |
Around criteria list() (2.x only) |
criteriaBuilder, results (after) |
beforeCriteriaBuilderCount / afterCriteriaBuilderCount |
Around criteria count() (2.x only) |
criteriaBuilder, count (after) |
beforeCriteriaBuilderGet / afterCriteriaBuilderGet |
Around criteria get() (2.x only) |
criteriaBuilder, result (after) |
onCriteriaBuilderAddition |
When a condition is added to a criteria (2.x only) |
criteriaBuilder, type |
properties is the application's ormSettings struct. Entity lifecycle events
(preInsert, postCommit, ...) are not interception points: they go to entity
methods and the global eventHandler, and only when eventHandling=true (1.x
fired them regardless). post_new itself is announced on every entityNew().
Listening
// OrmWatcher.bx
class {
function onORMQuery( data ) {
// 100 ms
if ( data.elapsedNanos > 100000000 ) {
writeLog( text="Slow ORM #data.kind#: #data.sql#", type="warning" );
}
}
function onORMException( data ) {
writeLog( text="ORM failure on #data.datasource#: #data.error.getMessage()#", type="error" );
}
}
Register it with boxRegisterInterceptor(), naming the events it listens to:
boxRegisterInterceptor(
interceptor : new OrmWatcher(),
points : [ "onORMQuery", "onORMException" ]
);
Settings
Set in this.ormSettings. All default to false.
| Setting |
Description |
announceQueryParams |
Include bound parameter values in onORMQuery. Values can be sensitive, so enable only where you need them |
generateStatistics |
Collect Hibernate statistics at startup for ORMService.getStatistics(). Collection has a small cost |
logSQL |
Log every generated SQL statement to orm.log |
Statistics
ORMService is a global service, reached through the runtime (Java interop).
Its methods take the ORM app name as a BoxLang Key:
import java:ortus.boxlang.runtime.BoxRuntime;
import java:ortus.boxlang.runtime.scopes.Key;
ormService = BoxRuntime::getInstance().getGlobalService( "ORMService" );
appKey = Key::of( appName ); // the appName from an event payload
stats = ormService.getStatistics( appKey );
// { appName, datasources : { myDS : { enabled, queryExecutionCount, ... } } }
// switch collection on or off at runtime, counters start from zero when enabled
ormService.setStatisticsEnabled( appKey, true );
When statistics are not collected, each datasource entry is only
{ enabled : false }. Enabled entries include sessionOpenCount, flushCount,
prepareStatementCount, transactionCount, queryExecutionCount,
queryExecutionMaxTime, queryExecutionMaxTimeQueryString, entity and
collection load/fetch/insert/update/delete counts, and second-level and query
cache hit/miss/put counts.
Logs
- bx-orm, Hibernate and (with
logSQL : true) SQL output all go to orm.log
in the BoxLang runtime logs/ directory.
- At DEBUG level, startup timings are logged per step:
ORM startup metric - entity file discovery: 42ms (187 candidate files found)
ORM startup metric - entity metadata parsing: 310ms (23 persistent entities found, sequential mode)
ORM startup metric - XML mapping generation: 88ms (23 mapping files generated)
ORM startup metric - Hibernate SessionFactory build time [myDatasource]: 1243ms
Diagnostics and Errors (2.x only)
diag = ormDiagnostics(); // never throws
if ( diag.status != "running" ) {
writeDump( diag.startupError ?: diag );
}
stats = ormGetSessionStatistics(); // this request's session, default datasource
// { entityCount, collectionCount, entityKeys : [ "User#5" ], collectionKeys : [ "User.orders#5" ] }
ormDiagnostics() returns status (running, failed, notStarted,
notEnabled), applicationName, hibernateVersion, startupError
({ at, type, message, detail }), datasources (entity names), entityCount,
warnings, key settings and this request's open sessions (with dirty).
- A failed
ormReload() keeps the previous ORM running; startupError says why.
- Every ORM error has a
type starting with orm (orm.query.syntax,
orm.constraint.unique, orm.stale, orm.lazy.noSession, ...). Catch by
prefix (catch ( "orm.constraint" e )) and read context from
e.extendedInfo (entity, property, hql, params, sql). In 1.x you catch
raw Hibernate exception classes instead.
Common Pitfalls
- ❌ Do NOT turn on
announceQueryParams in production without considering sensitive data in the values
- ❌ Do NOT assume flush counts are entity counts, they are statement counts
- ❌ Do NOT register the listener after startup if you need startup DDL, it will already have run
- ❌ Do NOT expect entity lifecycle events (
preInsert, postLoad, ...) as interception points; use eventHandling and an event handler
- ✅ Keep listeners cheap: they run synchronously on the thread executing the statement
- ✅ Use
kind and elapsedNanos for slow query logs, hql and entityName to find the caller
- ✅ Call
ormDiagnostics() first when the ORM misbehaves; it never throws
1---2name: bx-orm-observability3description: "Use this skill when monitoring or debugging bx-orm 2.x activity in BoxLang: the onORMQuery, onORMFlush and onORMException interception points, slow SQL and bound parameters, config-load, post_new and criteria interception points, Hibernate statistics via ORMService.getStatistics, orm.log SQL and startup metrics, ormDiagnostics(), ormGetSessionStatistics() and orm.* error types."4metadata:5 source: https://skillmd.com/skills/ortus-boxlang/bx-orm-observability6---78# bx-orm: Observability910> BoxLang is the AI-native software productivity platform for building, modernizing and running applications, with developers and AI agents working together.1112bx-orm announces events for SQL, flushes and failures through BoxLang's13interceptor service. Use them to build debuggers, monitors and slow query logs14without reaching into Hibernate.1516There is no cost when nothing listens: JDBC objects are only wrapped when a17listener exists as a connection is acquired, and payloads are built lazily.1819## Events2021| Event | Fires | Payload |22| --- | --- | --- |23| `onORMQuery` | After each JDBC statement. Selects fire when the result set closes, once the row count is known | `sql`, `kind`, `elapsedNanos`, `rows`, `datasource`, `appName`, `hql`, `entityName`, `error`, `params` |24| `onORMFlush` | After each session flush | `inserts`, `updates`, `deletes`, `elapsedNanos`, `datasource`, `appName` |25| `onORMException` | When a statement fails | `error`, `sql`, `datasource`, `appName` |2627### `onORMQuery` payload2829| Key | Description |30| --- | --- |31| `sql` | SQL text sent to the driver |32| `kind` | `select`, `insert`, `update`, `delete`, `ddl` or `other` |33| `elapsedNanos` | Execution time in nanoseconds (excludes reading rows) |34| `rows` | Rows returned (select), rows affected (DML), `-1` when unknown (DDL) |35| `datasource` | Datasource name |36| `appName` | Unique ORM application name |37| `hql` | HQL behind the statement when it came from `ormExecuteQuery()`, else `null` |38| `entityName` | Entity being loaded when it came from `entityLoad()` or `entityLoadByPK()`, else `null` |39| `error` | The `Throwable` if the statement failed, else `null` |40| `params` | Ordered array of bound values. **Only present when `announceQueryParams=true`** |4142A failed statement fires `onORMQuery` with `error` set and `onORMException`.43That includes SQL rejected when the statement is prepared. Startup DDL (for44example `dbcreate="dropcreate"`) is announced too when the listener registers45before the application starts.4647`onORMFlush` counts are statements run during the flush, not entities, so JDBC48batching can make them differ from the number of entities changed.4950### Other interception points5152| Point | When | Payload |53| --- | --- | --- |54| `ORMPreConfigLoad` | Before bx-orm reads an application's `ormSettings` | `properties`, `context` |55| `ORMPostConfigLoad` | After bx-orm reads an application's `ormSettings` | `properties`, `context` |56| `post_new` | When `entityNew()` creates an entity | `entityName`, `entity`, `context` |57| `beforeCriteriaBuilderList` / `afterCriteriaBuilderList` | Around criteria `list()` (2.x only) | `criteriaBuilder`, `results` (after) |58| `beforeCriteriaBuilderCount` / `afterCriteriaBuilderCount` | Around criteria `count()` (2.x only) | `criteriaBuilder`, `count` (after) |59| `beforeCriteriaBuilderGet` / `afterCriteriaBuilderGet` | Around criteria `get()` (2.x only) | `criteriaBuilder`, `result` (after) |60| `onCriteriaBuilderAddition` | When a condition is added to a criteria (2.x only) | `criteriaBuilder`, `type` |6162`properties` is the application's `ormSettings` struct. Entity lifecycle events63(`preInsert`, `postCommit`, ...) are not interception points: they go to entity64methods and the global `eventHandler`, and only when `eventHandling=true` (1.x65fired them regardless). `post_new` itself is announced on every `entityNew()`.6667## Listening6869```javascript70// OrmWatcher.bx71class {7273 function onORMQuery( data ) {74 // 100 ms75 if ( data.elapsedNanos > 100000000 ) {76 writeLog( text="Slow ORM #data.kind#: #data.sql#", type="warning" );77 }78 }7980 function onORMException( data ) {81 writeLog( text="ORM failure on #data.datasource#: #data.error.getMessage()#", type="error" );82 }8384}85```8687Register it with `boxRegisterInterceptor()`, naming the events it listens to:8889```javascript90boxRegisterInterceptor(91 interceptor : new OrmWatcher(),92 points : [ "onORMQuery", "onORMException" ]93);94```9596## Settings9798Set in `this.ormSettings`. All default to `false`.99100| Setting | Description |101| --- | --- |102| `announceQueryParams` | Include bound parameter values in `onORMQuery`. Values can be sensitive, so enable only where you need them |103| `generateStatistics` | Collect Hibernate statistics at startup for `ORMService.getStatistics()`. Collection has a small cost |104| `logSQL` | Log every generated SQL statement to `orm.log` |105106## Statistics107108`ORMService` is a global service, reached through the runtime (Java interop).109Its methods take the ORM app name as a BoxLang `Key`:110111```javascript112import java:ortus.boxlang.runtime.BoxRuntime;113import java:ortus.boxlang.runtime.scopes.Key;114115ormService = BoxRuntime::getInstance().getGlobalService( "ORMService" );116appKey = Key::of( appName ); // the appName from an event payload117118stats = ormService.getStatistics( appKey );119// { appName, datasources : { myDS : { enabled, queryExecutionCount, ... } } }120121// switch collection on or off at runtime, counters start from zero when enabled122ormService.setStatisticsEnabled( appKey, true );123```124125When statistics are not collected, each datasource entry is only126`{ enabled : false }`. Enabled entries include `sessionOpenCount`, `flushCount`,127`prepareStatementCount`, `transactionCount`, `queryExecutionCount`,128`queryExecutionMaxTime`, `queryExecutionMaxTimeQueryString`, entity and129collection load/fetch/insert/update/delete counts, and second-level and query130cache hit/miss/put counts.131132## Logs133134- bx-orm, Hibernate and (with `logSQL : true`) SQL output all go to `orm.log`135 in the BoxLang runtime `logs/` directory.136- At DEBUG level, startup timings are logged per step:137138```text139ORM startup metric - entity file discovery: 42ms (187 candidate files found)140ORM startup metric - entity metadata parsing: 310ms (23 persistent entities found, sequential mode)141ORM startup metric - XML mapping generation: 88ms (23 mapping files generated)142ORM startup metric - Hibernate SessionFactory build time [myDatasource]: 1243ms143```144145## Diagnostics and Errors (2.x only)146147```javascript148diag = ormDiagnostics(); // never throws149if ( diag.status != "running" ) {150 writeDump( diag.startupError ?: diag );151}152153stats = ormGetSessionStatistics(); // this request's session, default datasource154// { entityCount, collectionCount, entityKeys : [ "User#5" ], collectionKeys : [ "User.orders#5" ] }155```156157- `ormDiagnostics()` returns `status` (`running`, `failed`, `notStarted`,158 `notEnabled`), `applicationName`, `hibernateVersion`, `startupError`159 (`{ at, type, message, detail }`), `datasources` (entity names), `entityCount`,160 `warnings`, key `settings` and this request's open `sessions` (with `dirty`).161- A failed `ormReload()` keeps the previous ORM running; `startupError` says why.162- Every ORM error has a `type` starting with `orm` (`orm.query.syntax`,163 `orm.constraint.unique`, `orm.stale`, `orm.lazy.noSession`, ...). Catch by164 prefix (`catch ( "orm.constraint" e )`) and read context from165 `e.extendedInfo` (entity, property, `hql`, `params`, `sql`). In 1.x you catch166 raw Hibernate exception classes instead.167168## Common Pitfalls169170- ❌ Do NOT turn on `announceQueryParams` in production without considering sensitive data in the values171- ❌ Do NOT assume flush counts are entity counts, they are statement counts172- ❌ Do NOT register the listener after startup if you need startup DDL, it will already have run173- ❌ Do NOT expect entity lifecycle events (`preInsert`, `postLoad`, ...) as interception points; use `eventHandling` and an event handler174- ✅ Keep listeners cheap: they run synchronously on the thread executing the statement175- ✅ Use `kind` and `elapsedNanos` for slow query logs, `hql` and `entityName` to find the caller176- ✅ Call `ormDiagnostics()` first when the ORM misbehaves; it never throws