Skip to content

Commit

Permalink
Add logging for extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
esarver committed Oct 15, 2024
1 parent 686488a commit 9989f64
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 46 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how

- Added walkthrough document
- Added macOS support (LAN only)
- Added file logging for extension code

### Changed

Expand All @@ -34,6 +35,10 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how
- **tsp-toolkit-kic-cli**: Only call `readSTB` after a command or script is written to
the instrument

### Removed

- Removed VSCode Output pane logging

## [0.18.1]

### Added
Expand Down
18 changes: 13 additions & 5 deletions src/communicationmanager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
KicProcessMgr,
} from "./resourceManager"
import { createTerminal } from "./extension"
import { Log, SourceLocation } from "./logging"

export class CommunicationManager {
public connectionRE = /(?:(\w+)@)?(\d+.*)/
Expand Down Expand Up @@ -143,11 +144,11 @@ export class CommunicationManager {
kicTerminals.forEach((t) => {
const k: string =
t.name +
"@" +
(
(t.creationOptions as vscode.TerminalOptions)
?.shellArgs as string[]
)[1] ?? ""
"@" +
(
(t.creationOptions as vscode.TerminalOptions)
?.shellArgs as string[]
)[1]
kicDict[k] = t
})
if ((await vscode.window.showInputBox(options)) != undefined) {
Expand Down Expand Up @@ -181,13 +182,18 @@ export class CommunicationManager {
address: string,
filePath?: string,
): [info: string, verified_name?: string] {
const LOGLOC: SourceLocation = {
file: "extension.ts",
func: `CommunicationManager.createTerminal("${term_name}", "${connType.toString()}", "${address}", "${filePath ?? ""}")`,
}
let res: [string, string?] = ["", undefined]
const maxerr: number =
vscode.workspace.getConfiguration("tsp").get("errorLimit") ?? 0

switch (connType) {
case IoType.Lan:
{
Log.trace("Connecting via LAN", LOGLOC)
const parts = address.match(CONNECTION_RE)
if (parts == null) return ["", undefined]
const ip_addr = parts[2]
Expand All @@ -203,6 +209,7 @@ export class CommunicationManager {
break
case IoType.Usb:
{
Log.trace("Connecting via USB", LOGLOC)
let unique_string = address
const string_split = address.split("@")
if (string_split.length > 1) {
Expand All @@ -219,6 +226,7 @@ export class CommunicationManager {
break
case IoType.Visa:
{
Log.trace("Connecting via VISA", LOGLOC)
let unique_string = address
const string_split = address.split("@")
if (string_split.length > 1) {
Expand Down
57 changes: 54 additions & 3 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ export function createTerminal(
model_serial?: string,
command_text?: string,
): boolean {
const LOGLOC: SourceLocation = {
file: "extension.ts",
func: `createTerminal("${connection_string}", "${model_serial}", "${command_text}")`,
}
//'example@5e6:2461@2' OR '[email protected]'
let res: [string, string?] = ["", undefined]
let ip = connection_string
Expand All @@ -55,17 +59,26 @@ export function createTerminal(
}

if (_connHelper.IPTest(ip)) {
Log.debug("Connection type was determined to be LAN", LOGLOC)
//LAN
Log.trace("Creating terminal", LOGLOC)
res = _activeConnectionManager?.createTerminal(
name,
IoType.Lan,
connection_string,
command_text,
)

//const instr_to_save: string = "Lan:" + model_serial_no
Log.trace(
`createTerminal responded with '${res.toString().replace("\n", "").trim()}'`,
LOGLOC,
)
const info = res[0].replace("\n", "")
if (info == "") {
Log.trace(
"Unable to read response from createTerminal, could not connect to instrument",
LOGLOC,
)
void vscode.window.showErrorMessage(
"Unable to connect to instrument",
)
Expand All @@ -74,8 +87,14 @@ export function createTerminal(
name = res[1] == undefined ? name : res[1]
const port_number = "5025"

Log.trace(
`Details from createTerminal - info: "${info}", name: "${name}"`,
LOGLOC,
)
Log.trace("Saving connection", LOGLOC)
_instrExplorer.saveWhileConnect(ip, IoType.Lan, info, name, port_number)
} else {
Log.debug("Connection type was determined to be VISA", LOGLOC)
//VISA
//This only works if selected from Instrument discovery
if (name == "") {
Expand All @@ -87,16 +106,27 @@ export function createTerminal(
connection_string,
command_text,
)
Log.trace(`createTerminal responded with '${res.toString()}'`, LOGLOC)

const info = res[0].replace("\n", "")
if (info == "") {
Log.trace(
"Unable to read response from createTerminal, could not connect to instrument",
LOGLOC,
)
void vscode.window.showErrorMessage(
"Unable to connect to instrument",
)
return false
}
name = res[1] == undefined ? name : res[1]

Log.trace(
`Details from createTerminal - info: "${info}", name: "${name}"`,
LOGLOC,
)

Log.trace("Saving connection", LOGLOC)
_instrExplorer.saveWhileConnect(ip, IoType.Visa, info, name, undefined)
}
return true
Expand Down Expand Up @@ -256,7 +286,10 @@ function updateExtensionSettings() {
.getConfiguration("tsp")
.update(setting, undefined, true)
.then(() => {
Log.info(`Setting \`${setting}\` removed`)
Log.info(
`Setting \`${setting}\` removed`,
LOGLOC,
)
void vscode.window.showInformationMessage(
"removed setting: " + setting,
)
Expand Down Expand Up @@ -505,13 +538,31 @@ async function startRename(def: unknown): Promise<void> {
}

function connectCmd(def: object) {
const LOGLOC: SourceLocation = {
file: "extension.ts",
func: `connectCmd(${String(def)})`,
}

Log.trace("Fetching connection args", LOGLOC)
const [connection_str, model_serial] =
_instrExplorer.fetchConnectionArgs(def)

Log.trace(
`Connection string: '${connection_str}', Model serial: '${model_serial}'`,
LOGLOC,
)

if (_activeConnectionManager?.connectionRE.test(connection_str)) {
Log.trace("Connection string is valid. Creating Terminal", LOGLOC)
createTerminal(connection_str, model_serial)
} else {
void vscode.window.showErrorMessage("Unable to connect.")
Log.error(
"Connection string is invalid. Unable to connect to instrument.",
LOGLOC,
)
void vscode.window.showErrorMessage(
`Unable to connect. "${connection_str}" is not a valid connection string.`,
)
}
}

Expand Down
20 changes: 19 additions & 1 deletion src/instruments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
KicProcessMgr,
} from "./resourceManager"
import { LOG_DIR } from "./utility"
import { Log, SourceLocation } from "./logging"
//import { LoggerManager } from "./logging"

const DISCOVERY_TIMEOUT = 5
Expand Down Expand Up @@ -740,7 +741,12 @@ export class NewTDPModel {

//add from connect
public addFromConnectToSavedList(ioType: IoType, instr_details: InstrInfo) {
const LOGLOC: SourceLocation = {
file: "instruments.ts",
func: `NewTDPModel.addFromConnectToSavedList("${ioType.toString()}", "${String(instr_details)}")`,
}
if (instr_details != undefined) {
Log.trace("Adding instrument to list", LOGLOC)
this._savedNodeProvider?.saveInstrToList(
DiscoveryHelper.createUniqueID(instr_details),
)
Expand Down Expand Up @@ -768,8 +774,11 @@ export class NewTDPModel {
saved_list ?? [],
true,
)
break
}
return
}
Log.warn("Instrument details not provided", LOGLOC)
}

public addSavedList(instr: unknown) {
Expand Down Expand Up @@ -1223,6 +1232,11 @@ export class InstrTDP implements newTDP {
ioType: IoType,
instr_details: InstrInfo,
): void {
const LOGLOC: SourceLocation = {
file: "instruments.ts",
func: `InstrTDP.saveInstrumentFromConnect("${ioType.toString()}", "${String(instr_details)}")`,
}
Log.trace("Add from connect to saved list", LOGLOC)
this.instrModel?.addFromConnectToSavedList(ioType, instr_details)
this.reloadTreeData()
}
Expand Down Expand Up @@ -1423,6 +1437,10 @@ export class InstrumentsExplorer {
friendly_name: string,
port: string | undefined,
) {
const LOGLOC: SourceLocation = {
file: "instruments.ts",
func: `InstrumentExplorer.saveWhileConnect("${ip}", "${ioType.toString()}", "${info}", "${friendly_name}", "${port}")`,
}
const _info = <IIDNInfo>JSON.parse(info)
const __info = new InstrInfo()
__info.io_type = ioType
Expand All @@ -1438,7 +1456,7 @@ export class InstrumentsExplorer {
const categ = instr_map.get(_info.model)
if (categ != undefined) __info.instr_categ = categ

//FriendlyNameMgr.checkandAddFriendlyName(__info, friendly_name)
Log.trace("Saving Instrument", LOGLOC)

this.treeDataProvider?.saveInstrumentFromConnect(ioType, __info)
}
Expand Down
31 changes: 20 additions & 11 deletions src/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ enum LogLevel {
DEBUG = 1,
INFO = 2,
WARN = 3,
CRITICAL = 4,
ERROR = 4,
}

const LOGLEVEL_PAD = 8
const LOGLEVEL_PAD = 5

function logLevelToString(level: LogLevel): string {
switch (level) {
Expand All @@ -22,54 +22,59 @@ function logLevelToString(level: LogLevel): string {
return "INFO"
case LogLevel.WARN:
return "WARN"
case LogLevel.CRITICAL:
return "CRITICAL"
case LogLevel.ERROR:
return "ERROR"
}
}
export class Log {
/**
* Write a trace-level log to the log file.
*
* @param msg The message to write to the log file
* @param location The location in which the log took place
*/
public static trace(msg: string, location?: SourceLocation): void {
public static trace(msg: string, location: SourceLocation): void {
Log.instance().writeln(new Date(), LogLevel.TRACE, msg, location)
}

/**
* Write a debug-level log to the log file.
*
* @param msg The message to write to the log file
* @param location The location in which the log took place
*/
public static debug(msg: string, location?: SourceLocation): void {
public static debug(msg: string, location: SourceLocation): void {
Log.instance().writeln(new Date(), LogLevel.DEBUG, msg, location)
}

/**
* Write an info-level log to the log file.
*
* @param msg The message to write to the log file
* @param location The location in which the log took place
*/
public static info(msg: string, location?: SourceLocation): void {
public static info(msg: string, location: SourceLocation): void {
Log.instance().writeln(new Date(), LogLevel.INFO, msg, location)
}

/**
* Write a warning-level log to the log file.
*
* @param msg The message to write to the log file
* @param location The location in which the log took place
*/
public static warn(msg: string, location?: SourceLocation): void {
public static warn(msg: string, location: SourceLocation): void {
Log.instance().writeln(new Date(), LogLevel.WARN, msg, location)
}

/**
* Write a critical-level log to the log file.
*
* @param msg The message to write to the log file
* @param location The location in which the log took place
*/
public static crit(msg: string, location: SourceLocation): void {
Log.instance().writeln(new Date(), LogLevel.CRITICAL, msg, location)
public static error(msg: string, location?: SourceLocation): void {
Log.instance().writeln(new Date(), LogLevel.ERROR, msg, location)
}

private date: Date
Expand Down Expand Up @@ -138,7 +143,11 @@ export class Log {
): void {
//2024-10-15T12:34:56.789Z [INFO ] [email protected]: Some message to write to the log file
const content = `${timestamp.toISOString()} [${logLevelToString(level).padEnd(LOGLEVEL_PAD, " ")}] ${toString(location)}${msg}\n`
appendFileSync(this.file, content)
try {
appendFileSync(this.file, content)
} catch (err) {
console.error(err)
}
}
}

Expand Down
Loading

0 comments on commit 9989f64

Please sign in to comment.