feat: Add logs

This commit is contained in:
2025-06-06 19:32:31 +08:00
parent 9318cbca4e
commit 4d1a008106
9 changed files with 293 additions and 4 deletions

View File

@@ -1,19 +1,60 @@
using Cryville.Common.Font;
using Cryville.Common.Logging;
using Cryville.Common.Unity.UI;
using Cryville.Culture;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using UnityEngine;
using Logger = Cryville.Common.Logging.Logger;
namespace Cryville.EEW.Unity {
class App {
public static string AppDataPath { get; private set; }
public static Logger MainLogger { get; private set; }
static FileStream _logFileStream;
static StreamLoggerListener _logWriter;
static bool _init;
public static void Init() {
if (_init) return;
_init = true;
AppDataPath = Application.persistentDataPath;
var logPath = Directory.CreateDirectory(Path.Combine(AppDataPath, "logs"));
_logFileStream = new FileStream(
Path.Combine(
logPath.FullName,
string.Format(
CultureInfo.InvariantCulture,
"{0}.log",
DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture)
)
),
FileMode.Create, FileAccess.Write, FileShare.Read
);
_logWriter = new StreamLoggerListener(_logFileStream) { AutoFlush = true };
MainLogger = new Logger();
var listener = new InstantLoggerListener();
listener.Log += MainLogger.Log;
MainLogger.AddListener(_logWriter);
Application.logMessageReceivedThreaded += OnInternalLog;
MainLogger.Log(1, "App", null, "App Version: {0}", Application.version);
MainLogger.Log(1, "App", null, "Unity Version: {0}", Application.unityVersion);
MainLogger.Log(1, "App", null, "Operating System: {0}, Unity = {1}, Family = {2}", Environment.OSVersion, SystemInfo.operatingSystem, SystemInfo.operatingSystemFamily);
MainLogger.Log(1, "App", null, "Platform: Build = {0}, Unity = {1}", PlatformConfig.Name, Application.platform);
MainLogger.Log(1, "App", null, "Culture: {0}, UI = {1}, Unity = {2}", SharedCultures.CurrentCulture, SharedCultures.CurrentUICulture, Application.systemLanguage);
MainLogger.Log(1, "App", null, "Device: Model = {0}, Type = {1}", SystemInfo.deviceModel, SystemInfo.deviceType);
MainLogger.Log(1, "App", null, "Graphics: Name = {0}, Type = {1}, Vendor = {2}, Version = {3}", SystemInfo.graphicsDeviceName, SystemInfo.graphicsDeviceType, SystemInfo.graphicsDeviceVendor, SystemInfo.graphicsDeviceVersion);
MainLogger.Log(1, "App", null, "Processor: Count = {0}, Frequency = {1}MHz, Type = {2}", SystemInfo.processorCount, SystemInfo.processorFrequency, SystemInfo.processorType);
MainLogger.Log(1, "App", null, "Initializing font manager");
foreach (var res in Resources.LoadAll<TextAsset>("cldr/common/validity")) {
IdValidity.Load(LoadXmlDocument(res));
}
@@ -25,7 +66,10 @@ namespace Cryville.EEW.Unity {
};
TMPLocalizedText.DefaultShader = Resources.Load<Shader>(PlatformConfig.TextShader);
MainLogger.Log(1, "App", null, "Loading config");
SharedSettings.Instance.Init();
MainLogger.Log(1, "App", null, "Initialized");
}
static readonly Encoding _encoding = new UTF8Encoding(false, true);
@@ -40,5 +84,16 @@ namespace Cryville.EEW.Unity {
using var reader = XmlReader.Create(stream, _xmlSettings);
return XDocument.Load(reader);
}
static void OnInternalLog(string condition, string stackTrace, LogType type) {
var l = type switch {
LogType.Log => 1,
LogType.Assert => 2,
LogType.Warning => 3,
LogType.Error or LogType.Exception => 4,
_ => 1,
};
MainLogger.Log(l, "Internal", null, "{0}\n{1}", condition, stackTrace);
}
}
}

View File

@@ -40,7 +40,7 @@ namespace Cryville.EEW.Unity.Map {
_req.SendWebRequest();
}
catch (Exception ex) {
Debug.LogException(ex);
App.MainLogger.Log(4, "Map", null, "An error occurred when loading map tile {0}: {1}", _localFile, ex);
}
_isReady = false;
}
@@ -51,7 +51,7 @@ namespace Cryville.EEW.Unity.Map {
_sprite = Sprite.Create(_tex, new Rect(0, 0, _tex.width, _tex.height), Vector2.zero, _tex.height, 0, SpriteMeshType.FullRect, Vector4.zero, false);
}
else {
Debug.LogError(_texHandler.error);
App.MainLogger.Log(4, "Map", null, "An error occurred when loading map tile {0}: {1}", _localFile, _texHandler.error);
_localFile.Delete();
}
_req.Dispose();

View File

@@ -13,6 +13,7 @@ namespace Cryville.EEW.Unity {
};
protected override Stream Open(string path) {
App.MainLogger.Log(0, "Audio", null, "Opening audio file {0}", path);
path = Path.Combine(Application.streamingAssetsPath, "Sounds", path + ".ogg");
if (!File.Exists(path)) return null;
return new FileStream(path, FileMode.Open, FileAccess.Read);

View File

@@ -9,6 +9,7 @@ namespace Cryville.EEW.Unity {
readonly ISpVoice _voice;
public TTSWorker() : base(CreateSoundPlayer()) {
App.MainLogger.Log(1, "Audio", null, "Initializing TTS worker");
try {
_voice = new SpVoiceClass();
}
@@ -16,10 +17,12 @@ namespace Cryville.EEW.Unity {
}
static SoundPlayer CreateSoundPlayer() {
App.MainLogger.Log(1, "Audio", null, "Creating sound player");
try {
return new SoundPlayer();
}
catch (InvalidOperationException) {
catch (InvalidOperationException ex) {
App.MainLogger.Log(3, "Audio", null, "An error occurred when creating sound player: {0}", ex);
return null;
}
}
@@ -37,11 +40,13 @@ namespace Cryville.EEW.Unity {
(uint)(SpeechVoiceSpeakFlags.SVSFlagsAsync | SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak),
out _
);
App.MainLogger.Log(0, "Audio", null, "TTS ({0}): {1}", culture, content);
return Task.CompletedTask;
}
protected override void StopCurrent() {
if (_voice == null) return;
App.MainLogger.Log(0, "Audio", null, "TTS stopping current");
_voice.Skip("SENTENCE", int.MaxValue, out _);
}
}

View File

@@ -60,6 +60,7 @@ namespace Cryville.EEW.Unity {
}
void Start() {
App.MainLogger.Log(1, "App", null, "Initializing localized resources manager");
LocalizedResources.Init(new LocalizedResourcesManager());
RegisterViewModelGenerators(_worker);
RegisterTTSMessageGenerators(_worker);
@@ -73,6 +74,7 @@ namespace Cryville.EEW.Unity {
_worker.Reported += OnReported;
_grouper.GroupUpdated += OnGroupUpdated;
_grouper.GroupRemoved += OnGroupRemoved;
App.MainLogger.Log(1, "App", null, "Worker ready");
Task.Run(() => GatewayVerify(_cancellationTokenSource.Token)).ContinueWith(task => {
if (task.IsFaulted) {
OnReported(this, new() { Title = task.Exception.Message });
@@ -133,6 +135,7 @@ namespace Cryville.EEW.Unity {
bool _verified;
void BuildWorkers() {
App.MainLogger.Log(1, "App", null, "Building workers");
#if UNITY_EDITOR
_worker.AddWorker(new WolfxWorker(new Uri("ws://localhost:9995/wolfx")));
_worker.AddWorker(new JMAAtomWorker(new Uri("http://localhost:9095/eqvol.xml")));
@@ -215,7 +218,7 @@ namespace Cryville.EEW.Unity {
ReportViewModel _latestHistoryReport;
void OnReported(object sender, ReportViewModel e) {
if (e.Model is Exception && e.Model is not SourceWorkerNetworkException)
Debug.LogError(e);
App.MainLogger.Log(4, "Map", null, "Received an error from {0}: {1}", sender.GetType(), e.Model);
_grouper.Report(e);
_ongoingReportManager.Report(e);
_uiActionQueue.Enqueue(() => {

Binary file not shown.

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: 7aa0c56ccfdaf9443b58f26bf40eed01
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
Windows Store Apps: WindowsStoreApps
second:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,185 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Cryville.Common.Logging</name>
</assembly>
<members>
<member name="T:Cryville.Common.Logging.Logger">
<summary>
A logger.
</summary>
</member>
<member name="M:Cryville.Common.Logging.Logger.AddListener(Cryville.Common.Logging.LoggerListener)">
<summary>
Attaches a listener to the logger.
</summary>
<param name="listener">The logger listener.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.RemoveListener(Cryville.Common.Logging.LoggerListener)">
<summary>
Detaches a listener from the logger.
</summary>
<param name="listener">The logger listener.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.Log(System.Int32,System.String,System.String,System.Object[])">
<summary>
Logs to the logger.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="format">The format string.</param>
<param name="args">The arguments for formatting.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.Log(System.Int32,System.String,System.IFormatProvider,System.String,System.Object[])">
<summary>
Logs to the logger.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="provider">The format provider.</param>
<param name="format">The format string.</param>
<param name="args">The arguments for formatting.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.Log(System.Int32,System.String,System.String)">
<summary>
Logs to the logger.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">The message.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.Log(System.Int32,System.String,System.Char[])">
<summary>
Logs to the logger.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">An array of <see cref="T:System.Char" /> containing the message.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.Log(System.Int32,System.String,System.Char[],System.Int32,System.Int32)">
<summary>
Logs to the logger.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">An array of <see cref="T:System.Char" /> containing the message.</param>
<param name="index">A zero-based index of the first character of the message within <paramref name="message" />.</param>
<param name="length">The length of the message.</param>
</member>
<member name="M:Cryville.Common.Logging.Logger.Log(System.Int32,System.String,System.Char*,System.Int32)">
<summary>
Logs to the logger.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">A pointer to the first character of the message.</param>
<param name="length">The length of the message.</param>
</member>
<member name="T:Cryville.Common.Logging.LoggerListener">
<summary>
A logger listener.
</summary>
</member>
<member name="M:Cryville.Common.Logging.LoggerListener.Dispose(System.Boolean)">
<summary>
Closes the logger listener and cleans up all the resources.
</summary>
<param name="disposing">Whether to clean up managed resources.</param>
</member>
<member name="M:Cryville.Common.Logging.LoggerListener.Dispose">
<summary>
Closes the logger listener.
</summary>
</member>
<member name="M:Cryville.Common.Logging.LoggerListener.OnLog(System.Int32,System.String,System.String)">
<summary>
Handles an incoming log.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">The message.</param>
</member>
<member name="M:Cryville.Common.Logging.LoggerListener.OnLog(System.Int32,System.String,System.Char[],System.Int32,System.Int32)">
<summary>
Handles an incoming log.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">An array of <see cref="T:System.Char" /> containing the message.</param>
<param name="index">A zero-based index of the first character of the message within <paramref name="message" />.</param>
<param name="length">The length of the message.</param>
</member>
<member name="M:Cryville.Common.Logging.LoggerListener.OnLog(System.Int32,System.String,System.Char*,System.Int32)">
<summary>
Handles an incoming log.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">A pointer to the first character of the message.</param>
<param name="length">The length of the message.</param>
</member>
<member name="T:Cryville.Common.Logging.InstantLoggerListener">
<summary>
A <see cref="T:Cryville.Common.Logging.LoggerListener" /> that calls a callback function on log.
</summary>
</member>
<member name="E:Cryville.Common.Logging.InstantLoggerListener.Log">
<summary>
Occurs when a log is logged to the logger.
</summary>
</member>
<member name="M:Cryville.Common.Logging.InstantLoggerListener.OnLog(System.Int32,System.String,System.String)">
<inheritdoc />
</member>
<member name="T:Cryville.Common.Logging.BufferedLoggerListener">
<summary>
A <see cref="T:Cryville.Common.Logging.LoggerListener" /> that buffers the logs for enumeration.
</summary>
</member>
<member name="M:Cryville.Common.Logging.BufferedLoggerListener.OnLog(System.Int32,System.String,System.String)">
<inheritdoc />
</member>
<member name="M:Cryville.Common.Logging.BufferedLoggerListener.Enumerate(Cryville.Common.Logging.LogHandler)">
<summary>
Enumerates the buffered logs.
</summary>
<param name="callback">The callback function to receive the logs.</param>
</member>
<member name="T:Cryville.Common.Logging.StreamLoggerListener">
<summary>
A <see cref="T:Cryville.Common.Logging.LoggerListener" /> that writes logs into a stream.
</summary>
<param name="stream">The stream.</param>
<param name="encoding">The encoding.</param>
</member>
<member name="M:Cryville.Common.Logging.StreamLoggerListener.#ctor(System.IO.Stream,System.Text.Encoding)">
<summary>
A <see cref="T:Cryville.Common.Logging.LoggerListener" /> that writes logs into a stream.
</summary>
<param name="stream">The stream.</param>
<param name="encoding">The encoding.</param>
</member>
<member name="M:Cryville.Common.Logging.StreamLoggerListener.#ctor(System.IO.Stream)">
<summary>
Creates an instance of the <see cref="T:Cryville.Common.Logging.StreamLoggerListener" /> class.
</summary>
<param name="stream">The stream.</param>
</member>
<member name="P:Cryville.Common.Logging.StreamLoggerListener.AutoFlush">
<summary>
Whether to flush the stream every time a log is written.
</summary>
</member>
<member name="M:Cryville.Common.Logging.StreamLoggerListener.OnLog(System.Int32,System.String,System.String)">
<inheritdoc />
</member>
<member name="T:Cryville.Common.Logging.LogHandler">
<summary>
Represents the method that will handle a log.
</summary>
<param name="level">The severity level.</param>
<param name="category">The category.</param>
<param name="message">The message.</param>
</member>
</members>
</doc>

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 72ded0675457e0348809193a9c1092b5
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: