Skip to content

Commit d643885

Browse files
committed
Move to homwgrown logger to allow for file rotation based on size
1 parent 87cffc0 commit d643885

File tree

5 files changed

+87
-33
lines changed

5 files changed

+87
-33
lines changed

src/lib/bluelink-regions/base.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { Config } from '../../config'
22
import { defaultImage } from '../../resources/defaultImage'
3-
import PersistedLog from '../scriptable-utils/io/PersistedLog'
3+
import { Logger } from '../logger'
44
const KEYCHAIN_CACHE_KEY = 'egmp-bluelink-cache'
55
export const DEFAULT_STATUS_CHECK_INTERVAL = 3600 * 1000
6-
const BLUELINK_LOG_FILE = 'egmp-bluelink-log'
6+
const BLUELINK_LOG_FILE = 'egmp-bluelink.log'
77
const DEFAULT_API_HOST = 'mybluelink.ca'
88
const DEFAULT_API_DOMAIN = `https://${DEFAULT_API_HOST}/tods/api/`
99

@@ -121,7 +121,7 @@ export class Bluelink {
121121
this.debugLastRequest = undefined
122122
this.tempLookup = undefined
123123
this.distanceUnit = 'km'
124-
this.logger = PersistedLog(BLUELINK_LOG_FILE)
124+
this.logger = new Logger(BLUELINK_LOG_FILE, 100)
125125
}
126126

127127
protected async superInit(config: Config, statusCheckInterval?: number) {
@@ -346,9 +346,10 @@ export class Bluelink {
346346
}),
347347
}
348348
try {
349-
if (this.config.debugLogging) await this.logger.log(`Sending request ${JSON.stringify(this.debugLastRequest)}`)
349+
if (this.config.debugLogging) this.logger.log(`Sending request ${JSON.stringify(this.debugLastRequest)}`)
350350
const json = await req.loadJSON()
351-
await this.logger.log(`response ${JSON.stringify(req.response)} data: ${JSON.stringify(json)}`)
351+
if (this.config.debugLogging)
352+
this.logger.log(`response ${JSON.stringify(req.response)} data: ${JSON.stringify(json)}`)
352353

353354
const checkResponse = props.validResponseFunction(req.response, json)
354355
if (!props.noRetry && checkResponse.retry) {
@@ -362,7 +363,7 @@ export class Bluelink {
362363
return { resp: req.response, json: json }
363364
} catch (error) {
364365
const errorString = `Failed to send request to ${props.url}, request ${JSON.stringify(this.debugLastRequest)} - error ${error}`
365-
if (this.config.debugLogging) await this.logger.log(error)
366+
if (this.config.debugLogging) this.logger.log(error)
366367
throw Error(errorString)
367368
}
368369
}

src/lib/bluelink-regions/canada.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ export class BluelinkCanada extends Bluelink {
129129
}
130130

131131
const error = `Login Failed: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
132-
if (this.config.debugLogging) await this.logger.log(error)
132+
if (this.config.debugLogging) this.logger.log(error)
133133
return undefined
134134
}
135135

@@ -143,7 +143,7 @@ export class BluelinkCanada extends Bluelink {
143143
})
144144
if (!this.requestResponseValid(resp.resp, resp.json).valid) {
145145
const error = `Failed to set car ${id}: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
146-
if (this.config.debugLogging) await this.logger.log(error)
146+
if (this.config.debugLogging) this.logger.log(error)
147147
throw Error(error)
148148
}
149149
}
@@ -177,7 +177,7 @@ export class BluelinkCanada extends Bluelink {
177177
}
178178
}
179179
const error = `Failed to retrieve vehicle list: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
180-
if (this.config.debugLogging) await this.logger.log(error)
180+
if (this.config.debugLogging) this.logger.log(error)
181181
throw Error(error)
182182
}
183183

@@ -270,7 +270,7 @@ export class BluelinkCanada extends Bluelink {
270270
}
271271

272272
const error = `Failed to retrieve vehicle status: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
273-
if (this.config.debugLogging) await this.logger.log(error)
273+
if (this.config.debugLogging) this.logger.log(error)
274274
throw Error(error)
275275
}
276276

@@ -289,7 +289,7 @@ export class BluelinkCanada extends Bluelink {
289289
return resp.json.result.pAuth
290290
}
291291
const error = `Failed to get auth code: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
292-
if (this.config.debugLogging) await this.logger.log(error)
292+
if (this.config.debugLogging) this.logger.log(error)
293293
throw Error(error)
294294
}
295295

@@ -314,7 +314,7 @@ export class BluelinkCanada extends Bluelink {
314314

315315
if (!this.requestResponseValid(resp.resp, resp.json).valid) {
316316
const error = `Failed to poll for command completion: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
317-
if (this.config.debugLogging) await this.logger.log(error)
317+
if (this.config.debugLogging) this.logger.log(error)
318318
throw Error(error)
319319
}
320320

@@ -366,7 +366,7 @@ export class BluelinkCanada extends Bluelink {
366366
return await this.pollForCommandCompletion(id, authCode, transactionId)
367367
}
368368
const error = `Failed to send lockUnlock command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
369-
if (this.config.debugLogging) await this.logger.log(error)
369+
if (this.config.debugLogging) this.logger.log(error)
370370
throw Error(error)
371371
}
372372

@@ -401,7 +401,7 @@ export class BluelinkCanada extends Bluelink {
401401
return await this.pollForCommandCompletion(id, authCode, transactionId)
402402
}
403403
const error = `Failed to send charge command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
404-
if (this.config.debugLogging) await this.logger.log(error)
404+
if (this.config.debugLogging) this.logger.log(error)
405405
throw Error(error)
406406
}
407407

@@ -446,7 +446,7 @@ export class BluelinkCanada extends Bluelink {
446446
return await this.pollForCommandCompletion(id, authCode, transactionId)
447447
}
448448
const error = `Failed to send climateOff command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
449-
if (this.config.debugLogging) await this.logger.log(error)
449+
if (this.config.debugLogging) this.logger.log(error)
450450
throw Error(error)
451451
}
452452

@@ -470,7 +470,7 @@ export class BluelinkCanada extends Bluelink {
470470
return await this.pollForCommandCompletion(id, authCode, transactionId)
471471
}
472472
const error = `Failed to send climateOff command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
473-
if (this.config.debugLogging) await this.logger.log(error)
473+
if (this.config.debugLogging) this.logger.log(error)
474474
throw Error(error)
475475
}
476476
}

src/lib/bluelink-regions/usa.ts

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,12 @@ export class BluelinkUSA extends Bluelink {
115115
}
116116

117117
const error = `Login Failed: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
118-
if (this.config.debugLogging) await this.logger.log(error)
118+
if (this.config.debugLogging) this.logger.log(error)
119119
return undefined
120120
}
121121

122122
protected async refreshTokens(): Promise<BluelinkTokens | undefined> {
123-
if (this.config.debugLogging) await this.logger.log('Refreshing tokens')
123+
if (this.config.debugLogging) this.logger.log('Refreshing tokens')
124124
const resp = await this.request({
125125
url: this.apiDomain + 'v2/ac/oauth/token/refresh',
126126
data: JSON.stringify({
@@ -139,7 +139,7 @@ export class BluelinkUSA extends Bluelink {
139139
}
140140

141141
const error = `Login Failed: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
142-
if (this.config.debugLogging) await this.logger.log(error)
142+
if (this.config.debugLogging) this.logger.log(error)
143143
return undefined
144144
}
145145

@@ -159,7 +159,6 @@ export class BluelinkUSA extends Bluelink {
159159
}
160160
}
161161

162-
await this.logger.log(`Choose car ${JSON.stringify(vehicle)}`)
163162
this.carVin = vehicle.vin
164163
this.carId = vehicle.regid
165164
return {
@@ -174,7 +173,7 @@ export class BluelinkUSA extends Bluelink {
174173
}
175174
}
176175
const error = `Failed to retrieve vehicle list: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
177-
if (this.config.debugLogging) await this.logger.log(error)
176+
if (this.config.debugLogging) this.logger.log(error)
178177
throw Error(error)
179178
}
180179

@@ -224,7 +223,7 @@ export class BluelinkUSA extends Bluelink {
224223
}
225224

226225
const error = `Failed to retrieve vehicle status: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
227-
if (this.config.debugLogging) await this.logger.log(error)
226+
if (this.config.debugLogging) this.logger.log(error)
228227
throw Error(error)
229228
}
230229

@@ -267,7 +266,7 @@ export class BluelinkUSA extends Bluelink {
267266
return await this.pollForCommandCompletion(resp)
268267
}
269268
const error = `Failed to send lockUnlock command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
270-
if (this.config.debugLogging) await this.logger.log(error)
269+
if (this.config.debugLogging) this.logger.log(error)
271270
throw Error(error)
272271
}
273272

@@ -301,7 +300,7 @@ export class BluelinkUSA extends Bluelink {
301300
return await this.pollForCommandCompletion(resp)
302301
}
303302
const error = `Failed to send charge command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
304-
if (this.config.debugLogging) await this.logger.log(error)
303+
if (this.config.debugLogging) this.logger.log(error)
305304
throw Error(error)
306305
}
307306

@@ -344,7 +343,7 @@ export class BluelinkUSA extends Bluelink {
344343
return await this.pollForCommandCompletion(resp)
345344
}
346345
const error = `Failed to send climateOff command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
347-
if (this.config.debugLogging) await this.logger.log(error)
346+
if (this.config.debugLogging) this.logger.log(error)
348347
throw Error(error)
349348
}
350349

@@ -363,7 +362,7 @@ export class BluelinkUSA extends Bluelink {
363362
return await this.pollForCommandCompletion(resp)
364363
}
365364
const error = `Failed to send climateOff command: ${JSON.stringify(resp.json)} request ${JSON.stringify(this.debugLastRequest)}`
366-
if (this.config.debugLogging) await this.logger.log(error)
365+
if (this.config.debugLogging) this.logger.log(error)
367366
throw Error(error)
368367
}
369368
}

src/lib/logger.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
const SCRIPTABLE_DIR = '/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents'
2+
const DEFAULT_MAX_SIZE = 100
3+
4+
const loggingDateStringOptions = {
5+
year: 'numeric',
6+
month: '2-digit',
7+
day: '2-digit',
8+
hour: '2-digit',
9+
minute: '2-digit',
10+
second: '2-digit',
11+
fractionalSecondDigits: 3,
12+
} as Intl.DateTimeFormatOptions
13+
14+
export class Logger {
15+
private filepath: string
16+
private maxSize: number
17+
private fm: FileManager
18+
19+
constructor(filename: string, maxSize?: number) {
20+
this.filepath = `${SCRIPTABLE_DIR}/${filename}`
21+
this.maxSize = maxSize || DEFAULT_MAX_SIZE
22+
this.fm = FileManager.iCloud()
23+
}
24+
25+
private rotateFileIfNeeded() {
26+
if (this.fm.fileSize(this.filepath) > this.maxSize) {
27+
const date = new Date()
28+
const df = new DateFormatter()
29+
df.dateFormat = 'yyyyMMddHHmmssZ'
30+
this.fm.move(this.filepath, this.filepath + '.' + df.string(date))
31+
}
32+
}
33+
34+
private formatLogEntry(data: string): string {
35+
const date = new Date()
36+
return `${date.toLocaleDateString(undefined, loggingDateStringOptions)} - ${data}`
37+
}
38+
39+
private writeFile(data: string) {
40+
this.fm.writeString(this.filepath, data)
41+
}
42+
43+
private readFile(): string {
44+
if (this.fm.fileExists(this.filepath)) return this.fm.readString(this.filepath)
45+
return ''
46+
}
47+
48+
public log(input: string) {
49+
this.rotateFileIfNeeded()
50+
let currentData = this.readFile()
51+
currentData = currentData + '\n' + this.formatLogEntry(input)
52+
this.writeFile(currentData)
53+
}
54+
}

src/widget.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
} from './lib/util'
1010
import { Bluelink, Status } from './lib/bluelink-regions/base'
1111
import { Config } from 'config'
12-
import PersistedLog from './lib/scriptable-utils/io/PersistedLog'
12+
import { Logger } from './lib/logger'
1313

1414
// Widget Config
1515
const DARK_MODE = true // Device.isUsingDarkAppearance(); // or set manually to (true or false)
@@ -32,7 +32,7 @@ const DEFAULT_STATUS_CHECK_INTERVAL_NIGHT = 3600 * 2 * 1000
3232
const DEFAULT_REMOTE_REFRESH_INTERVAL_NIGHT = 3600 * 6 * 1000 // max 1 remote refresh per night
3333
const DEFAULT_CHARGING_REMOTE_REFRESH_INTERVAL_NIGHT = 3600 * 4 * 1000 // max 2 remote refreshes per night
3434

35-
const WIDGET_LOG_FILE = 'egmp-bluelink-widget-log'
35+
const WIDGET_LOG_FILE = 'egmp-bluelink-widget.log'
3636

3737
interface WidgetRefreshCache {
3838
lastRemoteRefresh: number
@@ -52,7 +52,7 @@ export function deleteWidgetCache() {
5252
}
5353

5454
async function refreshDataForWidget(bl: Bluelink, config: Config): Promise<WidgetRefresh> {
55-
const logger = PersistedLog(WIDGET_LOG_FILE)
55+
const logger = new Logger(WIDGET_LOG_FILE, 100)
5656
let cache: WidgetRefreshCache | undefined = undefined
5757
const currentTimestamp = Date.now()
5858
const currentHour = new Date().getHours()
@@ -118,13 +118,13 @@ async function refreshDataForWidget(bl: Bluelink, config: Config): Promise<Widge
118118
) {
119119
// Note a remote refresh takes to long to wait for - so trigger it and set a small nextRefresh value to pick
120120
// up the remote data on the next widget refresh
121-
if (config.debugLogging) await logger.log('Doing Force Refresh')
121+
if (config.debugLogging) logger.log('Doing Force Refresh')
122122
bl.getStatus(true, true) // no await deliberatly
123123
sleep(500) // wait for API request to be actually sent in background
124124
cache.lastRemoteRefresh = currentTimestamp
125125
nextRefresh = new Date(Date.now() + 5 * 60 * 1000)
126126
} else {
127-
if (config.debugLogging) await logger.log('Doing API Refresh')
127+
if (config.debugLogging) logger.log('Doing API Refresh')
128128
status = await bl.getStatus(false, true)
129129
}
130130
} catch (_error) {
@@ -134,8 +134,8 @@ async function refreshDataForWidget(bl: Bluelink, config: Config): Promise<Widge
134134

135135
Keychain.set(KEYCHAIN_WIDGET_REFRESH_KEY, JSON.stringify(cache))
136136
if (config.debugLogging)
137-
await logger.log(
138-
`Current time: ${new Date().toLocaleString()}. Setting next refresh to ${nextRefresh.toLocaleString()}`,
137+
logger.log(
138+
`Current time: ${new Date().toLocaleString()}. Last Remote refresh: last refresh ${new Date(status.status.lastRemoteStatusCheck).toLocaleString()} Setting next refresh to ${nextRefresh.toLocaleString()}`,
139139
)
140140

141141
return {

0 commit comments

Comments
 (0)