Refactoring Log Logic

This commit is contained in:
suziwen 2024-06-29 10:46:25 +08:00
parent 962bc129cd
commit 3994518c00
13 changed files with 18670 additions and 73 deletions

View File

@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>SwitchyOmega Background</title>
</head>
<body>
<canvas id="canvas-icon"></canvas>
<script src="js/log_error.js"></script>
<script src="lib/FileSaver/FileSaver.min.js"></script>
<script src="js/omega_debug.js"></script>
<script src="js/background_preload.js"></script>
<script src="js/omega_pac.min.js"></script>
<script src="js/omega_target.min.js"></script>
<script src="js/omega_target_chromium_extension.min.js"></script>
<script src="img/icons/draw_omega.js"></script>
<script src="js/background.js"></script>
</body>
</html>

View File

@ -0,0 +1,108 @@
const logStore = idbKeyval.createStore('log-store', 'log-store');
const dayOfWeek = moment().format('E') // Day of Week (ISO), keep logs max 7 day
const logKey = 'zerolog-' + dayOfWeek
const logSequence = []
let isRunning = false
let splitStr = '\n------------------\n'
const originConsoleLog = console.log
const originConsoleError = console.error
const _logFn = async function(){
if (isRunning) return
isRunning = true
while (logSequence.length > 0) {
const str = logSequence.join('\n');
logSequence.length = 0;
let logInfo = await idbKeyval.get(logKey, logStore)
if (!logInfo || !logInfo.date) {
logInfo = { date: moment().format('YYYY-MM-DD'), val: ''}
}
let { date, val } = logInfo
if ( !date.endsWith(dayOfWeek)) {
val = ''
}
val += splitStr
splitStr = `\n`
val += str
await idbKeyval.set(logKey, { date, val }, logStore)
}
isRunning = false
}
const logFn = (str)=>{
logSequence.push(moment().format('YYYY-MM-DD HH:mm:ss ') + ` ` + str)
_logFn()
}
const replacerFn = (key, value)=>{
switch (key) {
case 'username':
case 'password':
case 'host':
case 'port':
return '<secret>'
default:
return value
}
}
const getStr = function (){
const strArgs = [...arguments].map((obj)=>{
let str = '';
try {
if (typeof obj == 'string') {
str = obj
} else {
str = JSON.stringify(obj, replacerFn, 4)
}
} catch(e){
try {
str = obj.toString()
} catch(e){
}
}
return str
})
return strArgs.join(' ')
}
const ZeroLog = function(){
logFn(getStr.apply(null, arguments))
}
const _lastErrorLogFn = async ()=>{
if (_lastErrorLogFn.isRunning) return
_lastErrorLogFn.isRunning = true
while (_lastErrorLogFn.val) {
const val = _lastErrorLogFn.val
_lastErrorLogFn.val = ''
await idbKeyval.set('lastError', val, logStore)
}
_lastErrorLogFn.isRunning = false
}
const lastErrorLogFn = async ()=>{
const val = getStr.apply(null, arguments)
_lastErrorLogFn.val = val
_lastErrorLogFn()
}
globalThis.ZeroLogInfo = function() {
originConsoleLog.apply(null, arguments)
ZeroLog.apply(null, ['[INFO]', ...arguments])
}
globalThis.ZeroLogError = function(){
originConsoleError.apply(null, arguments)
ZeroLog.apply(null, ['[ERROR]', ...arguments])
lastErrorLogFn.apply(null, arguments)
}
globalThis.ZeroLogClear = async function(){
await idbKeyval.clear(logStore)
}
console.log = ZeroLogInfo
console.error = ZeroLogError

View File

@ -1,10 +1,12 @@
import "./js/background_preload.js"
import "./idb-keyval.js"
import "./lib/idb-keyval.js"
import "./lib/moment-with-locales.js"
import "./localstorage-polyfill.js"
import "./csso.js"
import "./lib/csso.js"
import "./js/log_error.js"
import "./log.js"
//import "./lib/FileSaver/FileSaver.min.js"
import "./js/omega_debug.js"
//import "./js/omega_debug.js"
import "./js/omega_pac.min.js"
import "./js/omega_target.min.js"
import "./js/omega_target_chromium_extension.min.js"

View File

@ -5,23 +5,6 @@ Promise.longStackTraces()
OmegaTargetCurrent.Log = Object.create(OmegaTargetCurrent.Log)
Log = OmegaTargetCurrent.Log
_writeLogToLocalStorage = (content) ->
try
localStorage['log'] += content
catch _
# Maybe we have reached our limit here. See #1288. Try trimming it.
localStorage['log'] = content
Log.log = (args...) ->
console.log(args...)
content = args.map(Log.str.bind(Log)).join(' ') + '\n'
_writeLogToLocalStorage(content)
Log.error = (args...) ->
console.error(args...)
content = args.map(Log.str.bind(Log)).join(' ')
localStorage['logLastError'] = content
_writeLogToLocalStorage('ERROR: ' + content + '\n')
unhandledPromises = []
unhandledPromisesId = []
unhandledPromisesNextId = 1

View File

@ -1,41 +1,76 @@
logStore = idbKeyval.createStore('log-store', 'log-store')
isProcessing = false
window.OmegaDebug =
getProjectVersion: ->
chrome.runtime.getManifest().version
getExtensionVersion: ->
chrome.runtime.getManifest().version
downloadLog: ->
blob = new Blob [localStorage['log']], {type: "text/plain;charset=utf-8"}
filename = "OmegaLog_#{Date.now()}.txt"
saveAs(blob, filename)
return if isProcessing
isProcessing = true
idbKeyval.entries(logStore).then((entries) ->
zip = new JSZip()
zipFolder = zip.folder('ZeroOmega')
entries.forEach((entry) ->
if entry[0] != 'lastError'
zipFolder.file(entry[1].date + '.log', entry[1].val)
)
return zip.generateAsync({
compression: "DEFLATE",
compressionOptions: {
level: 9
},
type: 'blob'
})
).then((blob) ->
filename = "ZeroOmegaLog_#{Date.now()}.zip"
saveAs(blob, filename)
isProcessing = false
)
resetOptions: ->
localStorage.clear()
# Prevent options loading from sync storage after reload.
localStorage['omega.local.syncOptions'] = '"conflict"'
chrome.storage.local.clear()
chrome.runtime.reload()
return if isProcessing
isProcessing = true
Promise.all([
idbKeyval.clear(logStore),
chrome.storage.local.clear()
]).then( ->
localStorage.clear()
# Prevent options loading from sync storage after reload.
localStorage['omega.local.syncOptions'] = '"conflict"'
isProcessing = false
chrome.runtime.reload()
)
reportIssue: ->
url = 'https://github.com/FelisCatus/SwitchyOmega/issues/new?title=&body='
finalUrl = url
try
projectVersion = OmegaDebug.getProjectVersion()
extensionVersion = OmegaDebug.getExtensionVersion()
env =
extensionVersion: extensionVersion
projectVersion: extensionVersion
userAgent: navigator.userAgent
body = chrome.i18n.getMessage('popup_issueTemplate', [
env.projectVersion, env.userAgent
])
body ||= """
\n\n
<!-- Please write your comment ABOVE this line. -->
SwitchyOmega #{env.projectVersion}
#{env.userAgent}
"""
finalUrl = url + encodeURIComponent(body)
err = localStorage['logLastError']
if err
body += "\n```\n#{err}\n```"
finalUrl = (url + encodeURIComponent(body)).substr(0, 2000)
return if isProcessing
isProcessing = true
idbKeyval.get('lastError', logStore).then((lastError) ->
isProcessing = false
url = 'https://github.com/suziwen/ZeroOmega/issues/new?title=&body='
finalUrl = url
try
projectVersion = OmegaDebug.getProjectVersion()
extensionVersion = OmegaDebug.getExtensionVersion()
env =
extensionVersion: extensionVersion
projectVersion: extensionVersion
userAgent: navigator.userAgent
body = chrome.i18n.getMessage('popup_issueTemplate', [
env.projectVersion, env.userAgent
])
body ||= """
\n\n
<!-- Please write your comment ABOVE this line. -->
SwitchyOmega #{env.projectVersion}
#{env.userAgent}
"""
finalUrl = url + encodeURIComponent(body)
err = lastError or ''
if err
body += "\n```\n#{err}\n```"
finalUrl = (url + encodeURIComponent(body)).substr(0, 2000)
chrome.tabs.create(url: finalUrl)
chrome.tabs.create(url: finalUrl)
)

View File

@ -653,7 +653,7 @@ class Options
# updated profile.
###
updateProfile: (name, opt_bypass_cache) ->
@log.method('Options#updateProfile', this, arguments)
# @log.method('Options#updateProfile', this, arguments)
results = {}
OmegaPac.Profiles.each @_options, (key, profile) =>
if name?

13
omega-web/lib/jszip.min.js vendored Normal file

File diff suppressed because one or more lines are too long

18472
omega-web/lib/moment-with-locales.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
window.onerror = (message, url, line, col, err) ->
console.log('globalThis onerror', arguments)
log = localStorage['log'] || ''
if err?.stack
log += err.stack + '\n\n'

View File

@ -62,7 +62,6 @@ $script.ready ['angular'], ->
$script.ready ['angular', 'omega', 'omega-deps', 'angular-ui-router',
'jquery-ui', 'spectrum', 'filesaver', 'blob', 'angular-ladda',
'angular-sanitize', 'angular-i18n'], ->
$script 'js/style.js', 'om-style'
initInjector = angular.injector(['ng'])
$http = initInjector.get('$http')
$http.get('./lib/themes/themes.json').then((response) ->

View File

@ -72,6 +72,9 @@ html(lang='en' ng-controller='MasterCtrl' ng-csp)
span.glyphicon(class="{{alertIcons[alert.type]}}")
= ' '
| {{alert.i18n ? (alert.i18n | tr) : alert.message}}
script(src='lib/moment-with-locales.js')
script(src='lib/idb-keyval.js')
script(src='lib/jszip.min.js')
script(src='js/omega_debug.js')
script(src='js/log_error.js')
script(src='lib/script.js/script.min.js')