Skip to content

Commit

Permalink
feat: render results as JSON for json logger
Browse files Browse the repository at this point in the history
When the JSON logger type is being used (via --logger-type=json),
command results are rendered to the log as JSON objects instead of YAML
strings. This facilitates parsing e.g. by testing code and other
instrumentation.

Highlighted YAML remains the default rendering method (e.g. for the
basic and fancy loggers).
  • Loading branch information
thsig committed May 7, 2019
1 parent 6ba3105 commit 4ca179e
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 36 deletions.
8 changes: 2 additions & 6 deletions garden-service/src/commands/get/get-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import * as yaml from "js-yaml"
import { highlightYaml } from "../../util/util"
import { Command, CommandResult, CommandParams } from "../base"
import { ConfigDump } from "../../garden"

Expand All @@ -18,10 +16,8 @@ export class GetConfigCommand extends Command {
async action({ garden, log }: CommandParams): Promise<CommandResult<ConfigDump>> {
const config = await garden.dumpConfig()

const yamlConfig = yaml.safeDump(config, { noRefs: true, skipInvalid: true })

// TODO: do a nicer print of this by default and use --yaml/--json options for exporting
log.info(highlightYaml(yamlConfig))
// TODO: do a nicer print of this by default
log.info({ data: config })

return { result: config }
}
Expand Down
6 changes: 1 addition & 5 deletions garden-service/src/commands/get/get-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import * as yaml from "js-yaml"
import { RenderedEdge, RenderedNode } from "../../config-graph"
import { highlightYaml } from "../../util/util"
import {
Command,
CommandResult,
Expand All @@ -29,9 +27,7 @@ export class GetGraphCommand extends Command {
const renderedGraph = graph.render()
const output: GraphOutput = { nodes: renderedGraph.nodes, relationships: renderedGraph.relationships }

const yamlGraph = yaml.safeDump(renderedGraph, { noRefs: true, skipInvalid: true })

log.info(highlightYaml(yamlGraph))
log.info({ data: renderedGraph })

return { result: output }

Expand Down
9 changes: 3 additions & 6 deletions garden-service/src/commands/get/get-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import * as yaml from "js-yaml"
import { highlightYaml, deepFilter } from "../../util/util"
import { deepFilter } from "../../util/util"
import {
Command,
CommandResult,
Expand All @@ -25,10 +24,8 @@ export class GetStatusCommand extends Command {
// TODO: we should change the status format because this will remove services called "detail"
const withoutDetail = deepFilter(status, (_, key) => key !== "detail")

const yamlStatus = yaml.safeDump(withoutDetail, { noRefs: true, skipInvalid: true })

// TODO: do a nicer print of this by default and use --yaml/--json options for exporting
log.info(highlightYaml(yamlStatus))
// TODO: do a nicer print of this by default
log.info({ data: withoutDetail })

return { result: status }
}
Expand Down
9 changes: 1 addition & 8 deletions garden-service/src/commands/get/get-task-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import * as yaml from "js-yaml"
import { ConfigGraph } from "../../config-graph"
import {
Command,
Expand All @@ -15,7 +14,6 @@ import {
StringParameter,
} from "../base"
import { logHeader } from "../../logger/util"
import { highlightYaml } from "../../util/util"
import { getTaskVersion } from "../../tasks/task"
import { RunTaskResult } from "../../types/plugin/outputs"
import chalk from "chalk"
Expand Down Expand Up @@ -75,13 +73,8 @@ export class GetTaskResultCommand extends Command<Args> {
startedAt: taskResult.startedAt,
completedAt: taskResult.completedAt,
}
const yamlStatus = yaml.safeDump(taskResult, {
noRefs: true,
skipInvalid: true,
})

log.info(highlightYaml(yamlStatus))

log.info({ data: taskResult })
return { result: output }
} else {
log.info(
Expand Down
9 changes: 2 additions & 7 deletions garden-service/src/commands/get/get-test-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@ import {
CommandParams,
StringParameter,
} from "../base"
import * as yaml from "js-yaml"
import { NotFoundError } from "../../exceptions"
import { TestResult } from "../../types/plugin/outputs"
import { getTestVersion } from "../../tasks/test"
import { findByName, getNames, highlightYaml } from "../../util/util"
import { findByName, getNames } from "../../util/util"
import { logHeader } from "../../logger/util"
import chalk from "chalk"

Expand Down Expand Up @@ -98,12 +97,8 @@ export class GetTestResultCommand extends Command<Args> {
version: testResult.version.versionString,
output: testResult.output,
}
const yamlStatus = yaml.safeDump(testResult, {
noRefs: true,
skipInvalid: true,
})

log.info(highlightYaml(yamlStatus))
log.info({ data: testResult })
return { result: output }
} else {
const errorMessage = `Could not find results for test '${testName}'`
Expand Down
1 change: 1 addition & 0 deletions garden-service/src/logger/log-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export interface TaskMetadata {

export interface UpdateOpts {
msg?: string | string[]
data?: any // to be rendered as e.g. YAML or JSON
section?: string
emoji?: EmojiName
symbol?: LogSymbol
Expand Down
18 changes: 15 additions & 3 deletions garden-service/src/logger/renderers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import hasAnsi = require("has-ansi")

import { LogEntry, EmojiName } from "./log-entry"
import { JsonLogEntry } from "./writers/json-terminal-writer"
import { highlightYaml } from "../util/util"

export type ToRender = string | ((...args: any[]) => string)
export type Renderer = [ToRender, any[]] | ToRender[]
Expand Down Expand Up @@ -133,6 +134,15 @@ export function renderMsg(entry: LogEntry): string {
return msg ? styleFn(msg) : ""
}

export function renderData(entry: LogEntry): string {
const { data } = entry.opts
if (!data) {
return ""
}
const asYaml = yaml.safeDump(data, { noRefs: true, skipInvalid: true })
return highlightYaml(asYaml)
}

export function renderSection(entry: LogEntry): string {
const { msg, section } = entry.opts
if (section && msg) {
Expand All @@ -151,8 +161,8 @@ export function renderDuration(entry: LogEntry): string {
}

export function formatForTerminal(entry: LogEntry): string {
const { msg, section, emoji, showDuration, symbol } = entry.opts
const empty = [msg, section, emoji, showDuration, symbol].every(val => val === undefined)
const { msg, data, section, emoji, showDuration, symbol } = entry.opts
const empty = [msg, data, section, emoji, showDuration, symbol].every(val => val === undefined)
if (empty) {
return ""
}
Expand All @@ -162,6 +172,7 @@ export function formatForTerminal(entry: LogEntry): string {
[renderSection, [entry]],
[renderEmoji, [entry]],
[renderMsg, [entry]],
[renderData, [entry]],
[renderDuration, [entry]],
["\n"],
])
Expand All @@ -186,9 +197,10 @@ export function cleanWhitespace(str) {
}

export function formatForJSON(entry: LogEntry): JsonLogEntry {
const { msg, section, showDuration, metadata } = entry.opts
const { msg, data, section, showDuration, metadata } = entry.opts
return {
msg: cleanForJSON(msg),
data,
metadata,
section: cleanForJSON(section),
durationMs: showDuration ? entry.getDuration(3) * 1000 : undefined,
Expand Down
4 changes: 3 additions & 1 deletion garden-service/src/logger/writers/json-terminal-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { formatForJSON } from "../renderers"

export interface JsonLogEntry {
msg: string,
data?: any,
section?: string,
durationMs?: number,
metadata?: LogEntryMetadata,
Expand All @@ -26,7 +27,8 @@ export class JsonTerminalWriter extends Writer {
const level = this.level || logger.level
if (level >= entry.level) {
const jsonEntry = formatForJSON(entry)
return jsonEntry.msg ? JSON.stringify(jsonEntry) : null
const empty = !(jsonEntry.msg || jsonEntry.data)
return empty ? null : JSON.stringify(jsonEntry)
}
return null
}
Expand Down

0 comments on commit 4ca179e

Please sign in to comment.