├── .gitignore
├── Cargo.toml
├── LICENSE.spdx
├── LICENSE_APACHE-2.0
├── LICENSE_MIT
├── README.md
├── banner.png
├── dist-js
├── index.d.ts
├── index.min.js
├── index.min.js.map
├── index.mjs
└── index.mjs.map
├── guest-js
└── index.ts
├── package.json
├── rollup.config.mjs
├── src
└── lib.rs
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tauri-plugin-log"
3 | version = "0.0.0"
4 | description = "Configurable logging for your Tauri app."
5 | authors = { workspace = true }
6 | license = { workspace = true }
7 | edition = { workspace = true }
8 | rust-version = { workspace = true }
9 |
10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
11 |
12 | [dependencies]
13 | serde = { workspace = true }
14 | serde_json = { workspace = true }
15 | tauri = { workspace = true }
16 | serde_repr = "0.1"
17 | byte-unit = "5"
18 | fern = "0.6"
19 | log = { workspace = true, features = ["kv_unstable"] }
20 | time = { version = "0.3", features = ["formatting", "local-offset"] }
21 |
22 | [features]
23 | colored = ["fern/colored"]
24 |
--------------------------------------------------------------------------------
/LICENSE.spdx:
--------------------------------------------------------------------------------
1 | SPDXVersion: SPDX-2.1
2 | DataLicense: CC0-1.0
3 | PackageName: tauri
4 | DataFormat: SPDXRef-1
5 | PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
6 | PackageHomePage: https://tauri.app
7 | PackageLicenseDeclared: Apache-2.0
8 | PackageLicenseDeclared: MIT
9 | PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
10 | PackageSummary: Tauri is a rust project that enables developers to make secure
11 | and small desktop applications using a web frontend.
12 |
13 | PackageComment: The package includes the following libraries; see
14 | Relationship information.
15 |
16 | Created: 2019-05-20T09:00:00Z
17 | PackageDownloadLocation: git://github.com/tauri-apps/tauri
18 | PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
19 | PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
20 | Creator: Person: Daniel Thompson-Yvetot
--------------------------------------------------------------------------------
/LICENSE_APACHE-2.0:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/LICENSE_MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 - Present Tauri Apps Contributors
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | Configurable logging for your Tauri app.
4 |
5 | ## Install
6 |
7 | _This plugin requires a Rust version of at least **1.67**_
8 |
9 | There are three general methods of installation that we can recommend.
10 |
11 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
12 | 2. Pull sources directly from Github using git tags / revision hashes (most secure)
13 | 3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
14 |
15 | Install the Core plugin by adding the following to your `Cargo.toml` file:
16 |
17 | `src-tauri/Cargo.toml`
18 |
19 | ```toml
20 | [dependencies]
21 | tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
22 | ```
23 |
24 | If you want the single instance mechanism to only trigger for semver compatible instances of your apps, for example if you expect users to have multiple installations of your app installed, you can add `features = ["semver"]` to the dependency declaration in `Cargo.toml`.
25 |
26 | Then you can install the JavaScript Guest bindings using your preferred JavaScript package manager:
27 |
28 | > Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
29 |
30 | ```sh
31 | pnpm add https://github.com/tauri-apps/tauri-plugin-log#v1
32 | # or
33 | npm add https://github.com/tauri-apps/tauri-plugin-log#v1
34 | # or
35 | yarn add https://github.com/tauri-apps/tauri-plugin-log#v1
36 | ```
37 |
38 | ## Usage
39 |
40 | First you need to register the core plugin with Tauri:
41 |
42 | `src-tauri/src/main.rs`
43 |
44 | ```rust
45 | use tauri_plugin_log::{LogTarget};
46 |
47 | fn main() {
48 | tauri::Builder::default()
49 | .plugin(tauri_plugin_log::Builder::default().targets([
50 | LogTarget::LogDir,
51 | LogTarget::Stdout,
52 | LogTarget::Webview,
53 | ]).build())
54 | .run(tauri::generate_context!())
55 | .expect("error while running tauri application");
56 | }
57 | ```
58 |
59 | Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
60 |
61 | ```javascript
62 | import { trace, info, error, attachConsole } from "tauri-plugin-log-api";
63 |
64 | // with LogTarget::Webview enabled this function will print logs to the browser console
65 | const detach = await attachConsole();
66 |
67 | trace("Trace");
68 | info("Info");
69 | error("Error");
70 |
71 | // detach the browser console from the log stream
72 | detach();
73 | ```
74 |
75 | To log from rust code, add the log crate to your `Cargo.toml`:
76 |
77 | ```toml
78 | [dependencies]
79 | log = "^0.4"
80 | ```
81 |
82 | Now, you can use the macros provided by the log crate to log messages from your backend. See the [docs](https://docs.rs/log/latest) for more details.
83 |
84 | ## Contributing
85 |
86 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
87 |
88 | ## Partners
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | |
98 |
99 |
100 |
101 |
102 | For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
103 |
104 | ## License
105 |
106 | Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
107 |
108 | MIT or MIT/Apache 2.0 where applicable.
109 |
--------------------------------------------------------------------------------
/banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tauri-apps/tauri-plugin-log/d33f0f4f8dbb02e705a83a471cdbbb9cb7b73a40/banner.png
--------------------------------------------------------------------------------
/dist-js/index.d.ts:
--------------------------------------------------------------------------------
1 | import { type UnlistenFn } from "@tauri-apps/api/event";
2 | export type LogOptions = {
3 | file?: string;
4 | line?: number;
5 | keyValues?: Record;
6 | };
7 | declare enum LogLevel {
8 | /**
9 | * The "trace" level.
10 | *
11 | * Designates very low priority, often extremely verbose, information.
12 | */
13 | Trace = 1,
14 | /**
15 | * The "debug" level.
16 | *
17 | * Designates lower priority information.
18 | */
19 | Debug = 2,
20 | /**
21 | * The "info" level.
22 | *
23 | * Designates useful information.
24 | */
25 | Info = 3,
26 | /**
27 | * The "warn" level.
28 | *
29 | * Designates hazardous situations.
30 | */
31 | Warn = 4,
32 | /**
33 | * The "error" level.
34 | *
35 | * Designates very serious errors.
36 | */
37 | Error = 5
38 | }
39 | /**
40 | * Logs a message at the error level.
41 | *
42 | * @param message
43 | *
44 | * # Examples
45 | *
46 | * ```js
47 | * import { error } from 'tauri-plugin-log-api';
48 | *
49 | * const err_info = "No connection";
50 | * const port = 22;
51 | *
52 | * error(`Error: ${err_info} on port ${port}`);
53 | * ```
54 | */
55 | export declare function error(message: string, options?: LogOptions): Promise;
56 | /**
57 | * Logs a message at the warn level.
58 | *
59 | * @param message
60 | *
61 | * # Examples
62 | *
63 | * ```js
64 | * import { warn } from 'tauri-plugin-log-api';
65 | *
66 | * const warn_description = "Invalid Input";
67 | *
68 | * warn(`Warning! {warn_description}!`);
69 | * ```
70 | */
71 | export declare function warn(message: string, options?: LogOptions): Promise;
72 | /**
73 | * Logs a message at the info level.
74 | *
75 | * @param message
76 | *
77 | * # Examples
78 | *
79 | * ```js
80 | * import { info } from 'tauri-plugin-log-api';
81 | *
82 | * const conn_info = { port: 40, speed: 3.20 };
83 | *
84 | * info(`Connected to port {conn_info.port} at {conn_info.speed} Mb/s`);
85 | * ```
86 | */
87 | export declare function info(message: string, options?: LogOptions): Promise;
88 | /**
89 | * Logs a message at the debug level.
90 | *
91 | * @param message
92 | *
93 | * # Examples
94 | *
95 | * ```js
96 | * import { debug } from 'tauri-plugin-log-api';
97 | *
98 | * const pos = { x: 3.234, y: -1.223 };
99 | *
100 | * debug(`New position: x: {pos.x}, y: {pos.y}`);
101 | * ```
102 | */
103 | export declare function debug(message: string, options?: LogOptions): Promise;
104 | /**
105 | * Logs a message at the trace level.
106 | *
107 | * @param message
108 | *
109 | * # Examples
110 | *
111 | * ```js
112 | * import { trace } from 'tauri-plugin-log-api';
113 | *
114 | * let pos = { x: 3.234, y: -1.223 };
115 | *
116 | * trace(`Position is: x: {pos.x}, y: {pos.y}`);
117 | * ```
118 | */
119 | export declare function trace(message: string, options?: LogOptions): Promise;
120 | interface RecordPayload {
121 | level: LogLevel;
122 | message: string;
123 | }
124 | type LoggerFn = (fn: RecordPayload) => void;
125 | /**
126 | * Attaches a listener for the log, and calls the passed function for each log entry.
127 | * @param fn
128 | *
129 | * @returns a function to cancel the listener.
130 | */
131 | export declare function attachLogger(fn: LoggerFn): Promise;
132 | /**
133 | * Attaches a listener that writes log entries to the console as they come in.
134 | *
135 | * @returns a function to cancel the listener.
136 | */
137 | export declare function attachConsole(): Promise;
138 | export {};
139 |
--------------------------------------------------------------------------------
/dist-js/index.min.js:
--------------------------------------------------------------------------------
1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 | /** @ignore */
5 | function uid() {
6 | return window.crypto.getRandomValues(new Uint32Array(1))[0];
7 | }
8 | /**
9 | * Transforms a callback function to a string identifier that can be passed to the backend.
10 | * The backend uses the identifier to `eval()` the callback.
11 | *
12 | * @return A unique identifier associated with the callback function.
13 | *
14 | * @since 1.0.0
15 | */
16 | function transformCallback(callback, once = false) {
17 | const identifier = uid();
18 | const prop = `_${identifier}`;
19 | Object.defineProperty(window, prop, {
20 | value: (result) => {
21 | if (once) {
22 | Reflect.deleteProperty(window, prop);
23 | }
24 | return callback === null || callback === void 0 ? void 0 : callback(result);
25 | },
26 | writable: false,
27 | configurable: true
28 | });
29 | return identifier;
30 | }
31 | /**
32 | * Sends a message to the backend.
33 | * @example
34 | * ```typescript
35 | * import { invoke } from '@tauri-apps/api/tauri';
36 | * await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' });
37 | * ```
38 | *
39 | * @param cmd The command name.
40 | * @param args The optional arguments to pass to the command.
41 | * @return A promise resolving or rejecting to the backend response.
42 | *
43 | * @since 1.0.0
44 | */
45 | async function invoke(cmd, args = {}) {
46 | return new Promise((resolve, reject) => {
47 | const callback = transformCallback((e) => {
48 | resolve(e);
49 | Reflect.deleteProperty(window, `_${error}`);
50 | }, true);
51 | const error = transformCallback((e) => {
52 | reject(e);
53 | Reflect.deleteProperty(window, `_${callback}`);
54 | }, true);
55 | window.__TAURI_IPC__({
56 | cmd,
57 | callback,
58 | error,
59 | ...args
60 | });
61 | });
62 | }
63 |
64 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
65 | // SPDX-License-Identifier: Apache-2.0
66 | // SPDX-License-Identifier: MIT
67 | /** @ignore */
68 | async function invokeTauriCommand(command) {
69 | return invoke('tauri', command);
70 | }
71 |
72 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
73 | // SPDX-License-Identifier: Apache-2.0
74 | // SPDX-License-Identifier: MIT
75 | /**
76 | * Unregister the event listener associated with the given name and id.
77 | *
78 | * @ignore
79 | * @param event The event name
80 | * @param eventId Event identifier
81 | * @returns
82 | */
83 | async function _unlisten(event, eventId) {
84 | return invokeTauriCommand({
85 | __tauriModule: 'Event',
86 | message: {
87 | cmd: 'unlisten',
88 | event,
89 | eventId
90 | }
91 | });
92 | }
93 | /**
94 | * Listen to an event from the backend.
95 | *
96 | * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
97 | * @param handler Event handler callback.
98 | * @return A promise resolving to a function to unlisten to the event.
99 | */
100 | async function listen$1(event, windowLabel, handler) {
101 | return invokeTauriCommand({
102 | __tauriModule: 'Event',
103 | message: {
104 | cmd: 'listen',
105 | event,
106 | windowLabel,
107 | handler: transformCallback(handler)
108 | }
109 | }).then((eventId) => {
110 | return async () => _unlisten(event, eventId);
111 | });
112 | }
113 |
114 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
115 | // SPDX-License-Identifier: Apache-2.0
116 | // SPDX-License-Identifier: MIT
117 | /**
118 | * The event system allows you to emit events to the backend and listen to events from it.
119 | *
120 | * This package is also accessible with `window.__TAURI__.event` when [`build.withGlobalTauri`](https://tauri.app/v1/api/config/#buildconfig.withglobaltauri) in `tauri.conf.json` is set to `true`.
121 | * @module
122 | */
123 | /**
124 | * @since 1.1.0
125 | */
126 | var TauriEvent;
127 | (function (TauriEvent) {
128 | TauriEvent["WINDOW_RESIZED"] = "tauri://resize";
129 | TauriEvent["WINDOW_MOVED"] = "tauri://move";
130 | TauriEvent["WINDOW_CLOSE_REQUESTED"] = "tauri://close-requested";
131 | TauriEvent["WINDOW_CREATED"] = "tauri://window-created";
132 | TauriEvent["WINDOW_DESTROYED"] = "tauri://destroyed";
133 | TauriEvent["WINDOW_FOCUS"] = "tauri://focus";
134 | TauriEvent["WINDOW_BLUR"] = "tauri://blur";
135 | TauriEvent["WINDOW_SCALE_FACTOR_CHANGED"] = "tauri://scale-change";
136 | TauriEvent["WINDOW_THEME_CHANGED"] = "tauri://theme-changed";
137 | TauriEvent["WINDOW_FILE_DROP"] = "tauri://file-drop";
138 | TauriEvent["WINDOW_FILE_DROP_HOVER"] = "tauri://file-drop-hover";
139 | TauriEvent["WINDOW_FILE_DROP_CANCELLED"] = "tauri://file-drop-cancelled";
140 | TauriEvent["MENU"] = "tauri://menu";
141 | TauriEvent["CHECK_UPDATE"] = "tauri://update";
142 | TauriEvent["UPDATE_AVAILABLE"] = "tauri://update-available";
143 | TauriEvent["INSTALL_UPDATE"] = "tauri://update-install";
144 | TauriEvent["STATUS_UPDATE"] = "tauri://update-status";
145 | TauriEvent["DOWNLOAD_PROGRESS"] = "tauri://update-download-progress";
146 | })(TauriEvent || (TauriEvent = {}));
147 | /**
148 | * Listen to an event. The event can be either global or window-specific.
149 | * See {@link Event.windowLabel} to check the event source.
150 | *
151 | * @example
152 | * ```typescript
153 | * import { listen } from '@tauri-apps/api/event';
154 | * const unlisten = await listen('error', (event) => {
155 | * console.log(`Got error in window ${event.windowLabel}, payload: ${event.payload}`);
156 | * });
157 | *
158 | * // you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
159 | * unlisten();
160 | * ```
161 | *
162 | * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
163 | * @param handler Event handler callback.
164 | * @returns A promise resolving to a function to unlisten to the event.
165 | * Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
166 | *
167 | * @since 1.0.0
168 | */
169 | async function listen(event, handler) {
170 | return listen$1(event, null, handler);
171 | }
172 |
173 | var LogLevel;
174 | (function (LogLevel) {
175 | /**
176 | * The "trace" level.
177 | *
178 | * Designates very low priority, often extremely verbose, information.
179 | */
180 | LogLevel[LogLevel["Trace"] = 1] = "Trace";
181 | /**
182 | * The "debug" level.
183 | *
184 | * Designates lower priority information.
185 | */
186 | LogLevel[LogLevel["Debug"] = 2] = "Debug";
187 | /**
188 | * The "info" level.
189 | *
190 | * Designates useful information.
191 | */
192 | LogLevel[LogLevel["Info"] = 3] = "Info";
193 | /**
194 | * The "warn" level.
195 | *
196 | * Designates hazardous situations.
197 | */
198 | LogLevel[LogLevel["Warn"] = 4] = "Warn";
199 | /**
200 | * The "error" level.
201 | *
202 | * Designates very serious errors.
203 | */
204 | LogLevel[LogLevel["Error"] = 5] = "Error";
205 | })(LogLevel || (LogLevel = {}));
206 | async function log(level, message, options) {
207 | var _a, _b;
208 | const traces = (_a = new Error().stack) === null || _a === void 0 ? void 0 : _a.split("\n").map((line) => line.split("@"));
209 | const filtered = traces === null || traces === void 0 ? void 0 : traces.filter(([name, location]) => {
210 | return name.length > 0 && location !== "[native code]";
211 | });
212 | const { file, line, keyValues } = options !== null && options !== void 0 ? options : {};
213 | let location = (_b = filtered === null || filtered === void 0 ? void 0 : filtered[0]) === null || _b === void 0 ? void 0 : _b.filter((v) => v.length > 0).join("@");
214 | if (location === "Error") {
215 | location = "webview::unknown";
216 | }
217 | await invoke("plugin:log|log", {
218 | level,
219 | message,
220 | location,
221 | file,
222 | line,
223 | keyValues,
224 | });
225 | }
226 | /**
227 | * Logs a message at the error level.
228 | *
229 | * @param message
230 | *
231 | * # Examples
232 | *
233 | * ```js
234 | * import { error } from 'tauri-plugin-log-api';
235 | *
236 | * const err_info = "No connection";
237 | * const port = 22;
238 | *
239 | * error(`Error: ${err_info} on port ${port}`);
240 | * ```
241 | */
242 | async function error(message, options) {
243 | await log(LogLevel.Error, message, options);
244 | }
245 | /**
246 | * Logs a message at the warn level.
247 | *
248 | * @param message
249 | *
250 | * # Examples
251 | *
252 | * ```js
253 | * import { warn } from 'tauri-plugin-log-api';
254 | *
255 | * const warn_description = "Invalid Input";
256 | *
257 | * warn(`Warning! {warn_description}!`);
258 | * ```
259 | */
260 | async function warn(message, options) {
261 | await log(LogLevel.Warn, message, options);
262 | }
263 | /**
264 | * Logs a message at the info level.
265 | *
266 | * @param message
267 | *
268 | * # Examples
269 | *
270 | * ```js
271 | * import { info } from 'tauri-plugin-log-api';
272 | *
273 | * const conn_info = { port: 40, speed: 3.20 };
274 | *
275 | * info(`Connected to port {conn_info.port} at {conn_info.speed} Mb/s`);
276 | * ```
277 | */
278 | async function info(message, options) {
279 | await log(LogLevel.Info, message, options);
280 | }
281 | /**
282 | * Logs a message at the debug level.
283 | *
284 | * @param message
285 | *
286 | * # Examples
287 | *
288 | * ```js
289 | * import { debug } from 'tauri-plugin-log-api';
290 | *
291 | * const pos = { x: 3.234, y: -1.223 };
292 | *
293 | * debug(`New position: x: {pos.x}, y: {pos.y}`);
294 | * ```
295 | */
296 | async function debug(message, options) {
297 | await log(LogLevel.Debug, message, options);
298 | }
299 | /**
300 | * Logs a message at the trace level.
301 | *
302 | * @param message
303 | *
304 | * # Examples
305 | *
306 | * ```js
307 | * import { trace } from 'tauri-plugin-log-api';
308 | *
309 | * let pos = { x: 3.234, y: -1.223 };
310 | *
311 | * trace(`Position is: x: {pos.x}, y: {pos.y}`);
312 | * ```
313 | */
314 | async function trace(message, options) {
315 | await log(LogLevel.Trace, message, options);
316 | }
317 | /**
318 | * Attaches a listener for the log, and calls the passed function for each log entry.
319 | * @param fn
320 | *
321 | * @returns a function to cancel the listener.
322 | */
323 | async function attachLogger(fn) {
324 | return await listen("log://log", (event) => {
325 | const { level } = event.payload;
326 | let { message } = event.payload;
327 | // Strip ANSI escape codes
328 | message = message.replace(
329 | // TODO: Investigate security/detect-unsafe-regex
330 | // eslint-disable-next-line no-control-regex
331 | /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
332 | fn({ message, level });
333 | });
334 | }
335 | /**
336 | * Attaches a listener that writes log entries to the console as they come in.
337 | *
338 | * @returns a function to cancel the listener.
339 | */
340 | async function attachConsole() {
341 | return attachLogger(({ level, message }) => {
342 | switch (level) {
343 | case LogLevel.Trace:
344 | console.log(message);
345 | break;
346 | case LogLevel.Debug:
347 | console.debug(message);
348 | break;
349 | case LogLevel.Info:
350 | console.info(message);
351 | break;
352 | case LogLevel.Warn:
353 | console.warn(message);
354 | break;
355 | case LogLevel.Error:
356 | console.error(message);
357 | break;
358 | default:
359 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
360 | throw new Error(`unknown log level ${level}`);
361 | }
362 | });
363 | }
364 |
365 | export { attachConsole, attachLogger, debug, error, info, trace, warn };
366 | //# sourceMappingURL=index.min.js.map
367 |
--------------------------------------------------------------------------------
/dist-js/index.min.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"index.min.js","sources":["../../../node_modules/.pnpm/@tauri-apps+api@1.6.0/node_modules/@tauri-apps/api/tauri.js","../../../node_modules/.pnpm/@tauri-apps+api@1.6.0/node_modules/@tauri-apps/api/helpers/tauri.js","../../../node_modules/.pnpm/@tauri-apps+api@1.6.0/node_modules/@tauri-apps/api/helpers/event.js","../../../node_modules/.pnpm/@tauri-apps+api@1.6.0/node_modules/@tauri-apps/api/event.js","../guest-js/index.ts"],"sourcesContent":["// Copyright 2019-2023 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n/** @ignore */\nfunction uid() {\n return window.crypto.getRandomValues(new Uint32Array(1))[0];\n}\n/**\n * Transforms a callback function to a string identifier that can be passed to the backend.\n * The backend uses the identifier to `eval()` the callback.\n *\n * @return A unique identifier associated with the callback function.\n *\n * @since 1.0.0\n */\nfunction transformCallback(callback, once = false) {\n const identifier = uid();\n const prop = `_${identifier}`;\n Object.defineProperty(window, prop, {\n value: (result) => {\n if (once) {\n Reflect.deleteProperty(window, prop);\n }\n return callback === null || callback === void 0 ? void 0 : callback(result);\n },\n writable: false,\n configurable: true\n });\n return identifier;\n}\n/**\n * Sends a message to the backend.\n * @example\n * ```typescript\n * import { invoke } from '@tauri-apps/api/tauri';\n * await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' });\n * ```\n *\n * @param cmd The command name.\n * @param args The optional arguments to pass to the command.\n * @return A promise resolving or rejecting to the backend response.\n *\n * @since 1.0.0\n */\nasync function invoke(cmd, args = {}) {\n return new Promise((resolve, reject) => {\n const callback = transformCallback((e) => {\n resolve(e);\n Reflect.deleteProperty(window, `_${error}`);\n }, true);\n const error = transformCallback((e) => {\n reject(e);\n Reflect.deleteProperty(window, `_${callback}`);\n }, true);\n window.__TAURI_IPC__({\n cmd,\n callback,\n error,\n ...args\n });\n });\n}\n/**\n * Convert a device file path to an URL that can be loaded by the webview.\n * Note that `asset:` and `https://asset.localhost` must be added to [`tauri.security.csp`](https://tauri.app/v1/api/config/#securityconfig.csp) in `tauri.conf.json`.\n * Example CSP value: `\"csp\": \"default-src 'self'; img-src 'self' asset: https://asset.localhost\"` to use the asset protocol on image sources.\n *\n * Additionally, `asset` must be added to [`tauri.allowlist.protocol`](https://tauri.app/v1/api/config/#allowlistconfig.protocol)\n * in `tauri.conf.json` and its access scope must be defined on the `assetScope` array on the same `protocol` object.\n * For example:\n * ```json\n * {\n * \"tauri\": {\n * \"allowlist\": {\n * \"protocol\": {\n * \"asset\": true,\n * \"assetScope\": [\"$APPDATA/assets/*\"]\n * }\n * }\n * }\n * }\n * ```\n *\n * @param filePath The file path.\n * @param protocol The protocol to use. Defaults to `asset`. You only need to set this when using a custom protocol.\n * @example\n * ```typescript\n * import { appDataDir, join } from '@tauri-apps/api/path';\n * import { convertFileSrc } from '@tauri-apps/api/tauri';\n * const appDataDirPath = await appDataDir();\n * const filePath = await join(appDataDirPath, 'assets/video.mp4');\n * const assetUrl = convertFileSrc(filePath);\n *\n * const video = document.getElementById('my-video');\n * const source = document.createElement('source');\n * source.type = 'video/mp4';\n * source.src = assetUrl;\n * video.appendChild(source);\n * video.load();\n * ```\n *\n * @return the URL that can be used as source on the webview.\n *\n * @since 1.0.0\n */\nfunction convertFileSrc(filePath, protocol = 'asset') {\n return window.__TAURI__.convertFileSrc(filePath, protocol);\n}\n\nexport { convertFileSrc, invoke, transformCallback };\n","import { invoke } from '../tauri.js';\n\n// Copyright 2019-2023 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n/** @ignore */\nasync function invokeTauriCommand(command) {\n return invoke('tauri', command);\n}\n\nexport { invokeTauriCommand };\n","import { invokeTauriCommand } from './tauri.js';\nimport { transformCallback } from '../tauri.js';\n\n// Copyright 2019-2023 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n/**\n * Unregister the event listener associated with the given name and id.\n *\n * @ignore\n * @param event The event name\n * @param eventId Event identifier\n * @returns\n */\nasync function _unlisten(event, eventId) {\n return invokeTauriCommand({\n __tauriModule: 'Event',\n message: {\n cmd: 'unlisten',\n event,\n eventId\n }\n });\n}\n/**\n * Emits an event to the backend.\n *\n * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.\n * @param [windowLabel] The label of the window to which the event is sent, if null/undefined the event will be sent to all windows\n * @param [payload] Event payload\n * @returns\n */\nasync function emit(event, windowLabel, payload) {\n await invokeTauriCommand({\n __tauriModule: 'Event',\n message: {\n cmd: 'emit',\n event,\n windowLabel,\n payload\n }\n });\n}\n/**\n * Listen to an event from the backend.\n *\n * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.\n * @param handler Event handler callback.\n * @return A promise resolving to a function to unlisten to the event.\n */\nasync function listen(event, windowLabel, handler) {\n return invokeTauriCommand({\n __tauriModule: 'Event',\n message: {\n cmd: 'listen',\n event,\n windowLabel,\n handler: transformCallback(handler)\n }\n }).then((eventId) => {\n return async () => _unlisten(event, eventId);\n });\n}\n/**\n * Listen to an one-off event from the backend.\n *\n * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.\n * @param handler Event handler callback.\n * @returns A promise resolving to a function to unlisten to the event.\n */\nasync function once(event, windowLabel, handler) {\n return listen(event, windowLabel, (eventData) => {\n handler(eventData);\n _unlisten(event, eventData.id).catch(() => { });\n });\n}\n\nexport { emit, listen, once };\n","import { listen as listen$1, once as once$1, emit as emit$1 } from './helpers/event.js';\n\n// Copyright 2019-2023 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n/**\n * The event system allows you to emit events to the backend and listen to events from it.\n *\n * This package is also accessible with `window.__TAURI__.event` when [`build.withGlobalTauri`](https://tauri.app/v1/api/config/#buildconfig.withglobaltauri) in `tauri.conf.json` is set to `true`.\n * @module\n */\n/**\n * @since 1.1.0\n */\nvar TauriEvent;\n(function (TauriEvent) {\n TauriEvent[\"WINDOW_RESIZED\"] = \"tauri://resize\";\n TauriEvent[\"WINDOW_MOVED\"] = \"tauri://move\";\n TauriEvent[\"WINDOW_CLOSE_REQUESTED\"] = \"tauri://close-requested\";\n TauriEvent[\"WINDOW_CREATED\"] = \"tauri://window-created\";\n TauriEvent[\"WINDOW_DESTROYED\"] = \"tauri://destroyed\";\n TauriEvent[\"WINDOW_FOCUS\"] = \"tauri://focus\";\n TauriEvent[\"WINDOW_BLUR\"] = \"tauri://blur\";\n TauriEvent[\"WINDOW_SCALE_FACTOR_CHANGED\"] = \"tauri://scale-change\";\n TauriEvent[\"WINDOW_THEME_CHANGED\"] = \"tauri://theme-changed\";\n TauriEvent[\"WINDOW_FILE_DROP\"] = \"tauri://file-drop\";\n TauriEvent[\"WINDOW_FILE_DROP_HOVER\"] = \"tauri://file-drop-hover\";\n TauriEvent[\"WINDOW_FILE_DROP_CANCELLED\"] = \"tauri://file-drop-cancelled\";\n TauriEvent[\"MENU\"] = \"tauri://menu\";\n TauriEvent[\"CHECK_UPDATE\"] = \"tauri://update\";\n TauriEvent[\"UPDATE_AVAILABLE\"] = \"tauri://update-available\";\n TauriEvent[\"INSTALL_UPDATE\"] = \"tauri://update-install\";\n TauriEvent[\"STATUS_UPDATE\"] = \"tauri://update-status\";\n TauriEvent[\"DOWNLOAD_PROGRESS\"] = \"tauri://update-download-progress\";\n})(TauriEvent || (TauriEvent = {}));\n/**\n * Listen to an event. The event can be either global or window-specific.\n * See {@link Event.windowLabel} to check the event source.\n *\n * @example\n * ```typescript\n * import { listen } from '@tauri-apps/api/event';\n * const unlisten = await listen('error', (event) => {\n * console.log(`Got error in window ${event.windowLabel}, payload: ${event.payload}`);\n * });\n *\n * // you need to call unlisten if your handler goes out of scope e.g. the component is unmounted\n * unlisten();\n * ```\n *\n * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.\n * @param handler Event handler callback.\n * @returns A promise resolving to a function to unlisten to the event.\n * Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.\n *\n * @since 1.0.0\n */\nasync function listen(event, handler) {\n return listen$1(event, null, handler);\n}\n/**\n * Listen to an one-off event. See {@link listen} for more information.\n *\n * @example\n * ```typescript\n * import { once } from '@tauri-apps/api/event';\n * interface LoadedPayload {\n * loggedIn: boolean,\n * token: string\n * }\n * const unlisten = await once('loaded', (event) => {\n * console.log(`App is loaded, loggedIn: ${event.payload.loggedIn}, token: ${event.payload.token}`);\n * });\n *\n * // you need to call unlisten if your handler goes out of scope e.g. the component is unmounted\n * unlisten();\n * ```\n *\n * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.\n * @returns A promise resolving to a function to unlisten to the event.\n * Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.\n *\n * @since 1.0.0\n */\nasync function once(event, handler) {\n return once$1(event, null, handler);\n}\n/**\n * Emits an event to the backend and all Tauri windows.\n * @example\n * ```typescript\n * import { emit } from '@tauri-apps/api/event';\n * await emit('frontend-loaded', { loggedIn: true, token: 'authToken' });\n * ```\n *\n * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.\n *\n * @since 1.0.0\n */\nasync function emit(event, payload) {\n return emit$1(event, undefined, payload);\n}\n\nexport { TauriEvent, emit, listen, once };\n",null],"names":["listen"],"mappings":"AAAA;AACA;AACA;AACA;AACA,SAAS,GAAG,GAAG;AACf,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,iBAAiB,CAAC,QAAQ,EAAE,IAAI,GAAG,KAAK,EAAE;AACnD,IAAI,MAAM,UAAU,GAAG,GAAG,EAAE;AAC5B,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;AACjC,IAAI,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE;AACxC,QAAQ,KAAK,EAAE,CAAC,MAAM,KAAK;AAC3B,YAAY,IAAI,IAAI,EAAE;AACtB,gBAAgB,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC;AACpD;AACA,YAAY,OAAO,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC;AACvF,SAAS;AACT,QAAQ,QAAQ,EAAE,KAAK;AACvB,QAAQ,YAAY,EAAE;AACtB,KAAK,CAAC;AACN,IAAI,OAAO,UAAU;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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AI;AAChB,gBAAA,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;gBACrB;YACF,KAAK,QAAQ,CAAC,IAAI;AAChB,gBAAA,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;gBACrB;YACF,KAAK,QAAQ,CAAC,KAAK;AACjB,gBAAA,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;gBACtB;AACF,YAAA;;AAEE,gBAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,KAAK,CAAA,CAAE,CAAC;;AAEnD,KAAC,CAAC;AACJ;;;;","x_google_ignoreList":[0,1,2,3]}
--------------------------------------------------------------------------------
/dist-js/index.mjs:
--------------------------------------------------------------------------------
1 | import { invoke } from '@tauri-apps/api/tauri';
2 | import { listen } from '@tauri-apps/api/event';
3 |
4 | var LogLevel;
5 | (function (LogLevel) {
6 | /**
7 | * The "trace" level.
8 | *
9 | * Designates very low priority, often extremely verbose, information.
10 | */
11 | LogLevel[LogLevel["Trace"] = 1] = "Trace";
12 | /**
13 | * The "debug" level.
14 | *
15 | * Designates lower priority information.
16 | */
17 | LogLevel[LogLevel["Debug"] = 2] = "Debug";
18 | /**
19 | * The "info" level.
20 | *
21 | * Designates useful information.
22 | */
23 | LogLevel[LogLevel["Info"] = 3] = "Info";
24 | /**
25 | * The "warn" level.
26 | *
27 | * Designates hazardous situations.
28 | */
29 | LogLevel[LogLevel["Warn"] = 4] = "Warn";
30 | /**
31 | * The "error" level.
32 | *
33 | * Designates very serious errors.
34 | */
35 | LogLevel[LogLevel["Error"] = 5] = "Error";
36 | })(LogLevel || (LogLevel = {}));
37 | async function log(level, message, options) {
38 | var _a, _b;
39 | const traces = (_a = new Error().stack) === null || _a === void 0 ? void 0 : _a.split("\n").map((line) => line.split("@"));
40 | const filtered = traces === null || traces === void 0 ? void 0 : traces.filter(([name, location]) => {
41 | return name.length > 0 && location !== "[native code]";
42 | });
43 | const { file, line, keyValues } = options !== null && options !== void 0 ? options : {};
44 | let location = (_b = filtered === null || filtered === void 0 ? void 0 : filtered[0]) === null || _b === void 0 ? void 0 : _b.filter((v) => v.length > 0).join("@");
45 | if (location === "Error") {
46 | location = "webview::unknown";
47 | }
48 | await invoke("plugin:log|log", {
49 | level,
50 | message,
51 | location,
52 | file,
53 | line,
54 | keyValues,
55 | });
56 | }
57 | /**
58 | * Logs a message at the error level.
59 | *
60 | * @param message
61 | *
62 | * # Examples
63 | *
64 | * ```js
65 | * import { error } from 'tauri-plugin-log-api';
66 | *
67 | * const err_info = "No connection";
68 | * const port = 22;
69 | *
70 | * error(`Error: ${err_info} on port ${port}`);
71 | * ```
72 | */
73 | async function error(message, options) {
74 | await log(LogLevel.Error, message, options);
75 | }
76 | /**
77 | * Logs a message at the warn level.
78 | *
79 | * @param message
80 | *
81 | * # Examples
82 | *
83 | * ```js
84 | * import { warn } from 'tauri-plugin-log-api';
85 | *
86 | * const warn_description = "Invalid Input";
87 | *
88 | * warn(`Warning! {warn_description}!`);
89 | * ```
90 | */
91 | async function warn(message, options) {
92 | await log(LogLevel.Warn, message, options);
93 | }
94 | /**
95 | * Logs a message at the info level.
96 | *
97 | * @param message
98 | *
99 | * # Examples
100 | *
101 | * ```js
102 | * import { info } from 'tauri-plugin-log-api';
103 | *
104 | * const conn_info = { port: 40, speed: 3.20 };
105 | *
106 | * info(`Connected to port {conn_info.port} at {conn_info.speed} Mb/s`);
107 | * ```
108 | */
109 | async function info(message, options) {
110 | await log(LogLevel.Info, message, options);
111 | }
112 | /**
113 | * Logs a message at the debug level.
114 | *
115 | * @param message
116 | *
117 | * # Examples
118 | *
119 | * ```js
120 | * import { debug } from 'tauri-plugin-log-api';
121 | *
122 | * const pos = { x: 3.234, y: -1.223 };
123 | *
124 | * debug(`New position: x: {pos.x}, y: {pos.y}`);
125 | * ```
126 | */
127 | async function debug(message, options) {
128 | await log(LogLevel.Debug, message, options);
129 | }
130 | /**
131 | * Logs a message at the trace level.
132 | *
133 | * @param message
134 | *
135 | * # Examples
136 | *
137 | * ```js
138 | * import { trace } from 'tauri-plugin-log-api';
139 | *
140 | * let pos = { x: 3.234, y: -1.223 };
141 | *
142 | * trace(`Position is: x: {pos.x}, y: {pos.y}`);
143 | * ```
144 | */
145 | async function trace(message, options) {
146 | await log(LogLevel.Trace, message, options);
147 | }
148 | /**
149 | * Attaches a listener for the log, and calls the passed function for each log entry.
150 | * @param fn
151 | *
152 | * @returns a function to cancel the listener.
153 | */
154 | async function attachLogger(fn) {
155 | return await listen("log://log", (event) => {
156 | const { level } = event.payload;
157 | let { message } = event.payload;
158 | // Strip ANSI escape codes
159 | message = message.replace(
160 | // TODO: Investigate security/detect-unsafe-regex
161 | // eslint-disable-next-line no-control-regex
162 | /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
163 | fn({ message, level });
164 | });
165 | }
166 | /**
167 | * Attaches a listener that writes log entries to the console as they come in.
168 | *
169 | * @returns a function to cancel the listener.
170 | */
171 | async function attachConsole() {
172 | return attachLogger(({ level, message }) => {
173 | switch (level) {
174 | case LogLevel.Trace:
175 | console.log(message);
176 | break;
177 | case LogLevel.Debug:
178 | console.debug(message);
179 | break;
180 | case LogLevel.Info:
181 | console.info(message);
182 | break;
183 | case LogLevel.Warn:
184 | console.warn(message);
185 | break;
186 | case LogLevel.Error:
187 | console.error(message);
188 | break;
189 | default:
190 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
191 | throw new Error(`unknown log level ${level}`);
192 | }
193 | });
194 | }
195 |
196 | export { attachConsole, attachLogger, debug, error, info, trace, warn };
197 | //# sourceMappingURL=index.mjs.map
198 |
--------------------------------------------------------------------------------
/dist-js/index.mjs.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"index.mjs","sources":["../guest-js/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;;AASA,IAAK,QA+BJ;AA/BD,CAAA,UAAK,QAAQ,EAAA;AACX;;;;AAIG;AACH,IAAA,QAAA,CAAA,QAAA,CAAA,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C,OAAO,MAAM,MAAM,CAAC,WAAW,EAAE,CAAC,KAA2B,KAAI;AAC/D,QAAA,MAAM,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC,OAAO;AAC/B,QAAA,IAAI,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO;;QAG/B,OAAO,GAAG,OAAO,CAAC,OAAO;;;QAGvB,6EAA6E,EAC7E,EAAE,CACH;AACD,QAAA,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AACxB,KAAC,CAAC;AACJ;AAEA;;;;AAIG;AACI,eAAe,aAAa,GAAA;IACjC,OAAO,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAiB,KAAI;QACxD,QAAQ,KAAK;YACX,KAAK,QAAQ,CAAC,KAAK;AACjB,gBAAA,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;gBACpB;YACF,KAAK,QAAQ,CAAC,KAAK;AACjB,gBAAA,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;gBACtB;YACF,KAAK,QAAQ,CAAC,IAAI;AAChB,gBAAA,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;gBACrB;YACF,KAAK,QAAQ,CAAC,IAAI;AAChB,gBAAA,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;gBACrB;YACF,KAAK,QAAQ,CAAC,KAAK;AACjB,gBAAA,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;gBACtB;AACF,YAAA;;AAEE,gBAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,KAAK,CAAA,CAAE,CAAC;;AAEnD,KAAC,CAAC;AACJ;;;;"}
--------------------------------------------------------------------------------
/guest-js/index.ts:
--------------------------------------------------------------------------------
1 | import { invoke } from "@tauri-apps/api/tauri";
2 | import { listen, type UnlistenFn, type Event } from "@tauri-apps/api/event";
3 |
4 | export type LogOptions = {
5 | file?: string;
6 | line?: number;
7 | keyValues?: Record;
8 | };
9 |
10 | enum LogLevel {
11 | /**
12 | * The "trace" level.
13 | *
14 | * Designates very low priority, often extremely verbose, information.
15 | */
16 | Trace = 1,
17 | /**
18 | * The "debug" level.
19 | *
20 | * Designates lower priority information.
21 | */
22 | Debug,
23 | /**
24 | * The "info" level.
25 | *
26 | * Designates useful information.
27 | */
28 | Info,
29 | /**
30 | * The "warn" level.
31 | *
32 | * Designates hazardous situations.
33 | */
34 | Warn,
35 | /**
36 | * The "error" level.
37 | *
38 | * Designates very serious errors.
39 | */
40 | Error,
41 | }
42 |
43 | async function log(
44 | level: LogLevel,
45 | message: string,
46 | options?: LogOptions,
47 | ): Promise {
48 | const traces = new Error().stack?.split("\n").map((line) => line.split("@"));
49 |
50 | const filtered = traces?.filter(([name, location]) => {
51 | return name.length > 0 && location !== "[native code]";
52 | });
53 |
54 | const { file, line, keyValues } = options ?? {};
55 |
56 | let location = filtered?.[0]?.filter((v) => v.length > 0).join("@");
57 | if (location === "Error") {
58 | location = "webview::unknown";
59 | }
60 |
61 | await invoke("plugin:log|log", {
62 | level,
63 | message,
64 | location,
65 | file,
66 | line,
67 | keyValues,
68 | });
69 | }
70 |
71 | /**
72 | * Logs a message at the error level.
73 | *
74 | * @param message
75 | *
76 | * # Examples
77 | *
78 | * ```js
79 | * import { error } from 'tauri-plugin-log-api';
80 | *
81 | * const err_info = "No connection";
82 | * const port = 22;
83 | *
84 | * error(`Error: ${err_info} on port ${port}`);
85 | * ```
86 | */
87 | export async function error(
88 | message: string,
89 | options?: LogOptions,
90 | ): Promise {
91 | await log(LogLevel.Error, message, options);
92 | }
93 |
94 | /**
95 | * Logs a message at the warn level.
96 | *
97 | * @param message
98 | *
99 | * # Examples
100 | *
101 | * ```js
102 | * import { warn } from 'tauri-plugin-log-api';
103 | *
104 | * const warn_description = "Invalid Input";
105 | *
106 | * warn(`Warning! {warn_description}!`);
107 | * ```
108 | */
109 | export async function warn(
110 | message: string,
111 | options?: LogOptions,
112 | ): Promise {
113 | await log(LogLevel.Warn, message, options);
114 | }
115 |
116 | /**
117 | * Logs a message at the info level.
118 | *
119 | * @param message
120 | *
121 | * # Examples
122 | *
123 | * ```js
124 | * import { info } from 'tauri-plugin-log-api';
125 | *
126 | * const conn_info = { port: 40, speed: 3.20 };
127 | *
128 | * info(`Connected to port {conn_info.port} at {conn_info.speed} Mb/s`);
129 | * ```
130 | */
131 | export async function info(
132 | message: string,
133 | options?: LogOptions,
134 | ): Promise {
135 | await log(LogLevel.Info, message, options);
136 | }
137 |
138 | /**
139 | * Logs a message at the debug level.
140 | *
141 | * @param message
142 | *
143 | * # Examples
144 | *
145 | * ```js
146 | * import { debug } from 'tauri-plugin-log-api';
147 | *
148 | * const pos = { x: 3.234, y: -1.223 };
149 | *
150 | * debug(`New position: x: {pos.x}, y: {pos.y}`);
151 | * ```
152 | */
153 | export async function debug(
154 | message: string,
155 | options?: LogOptions,
156 | ): Promise {
157 | await log(LogLevel.Debug, message, options);
158 | }
159 |
160 | /**
161 | * Logs a message at the trace level.
162 | *
163 | * @param message
164 | *
165 | * # Examples
166 | *
167 | * ```js
168 | * import { trace } from 'tauri-plugin-log-api';
169 | *
170 | * let pos = { x: 3.234, y: -1.223 };
171 | *
172 | * trace(`Position is: x: {pos.x}, y: {pos.y}`);
173 | * ```
174 | */
175 | export async function trace(
176 | message: string,
177 | options?: LogOptions,
178 | ): Promise {
179 | await log(LogLevel.Trace, message, options);
180 | }
181 |
182 | interface RecordPayload {
183 | level: LogLevel;
184 | message: string;
185 | }
186 |
187 | type LoggerFn = (fn: RecordPayload) => void;
188 |
189 | /**
190 | * Attaches a listener for the log, and calls the passed function for each log entry.
191 | * @param fn
192 | *
193 | * @returns a function to cancel the listener.
194 | */
195 | export async function attachLogger(fn: LoggerFn): Promise {
196 | return await listen("log://log", (event: Event) => {
197 | const { level } = event.payload;
198 | let { message } = event.payload;
199 |
200 | // Strip ANSI escape codes
201 | message = message.replace(
202 | // TODO: Investigate security/detect-unsafe-regex
203 | // eslint-disable-next-line no-control-regex
204 | /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
205 | "",
206 | );
207 | fn({ message, level });
208 | });
209 | }
210 |
211 | /**
212 | * Attaches a listener that writes log entries to the console as they come in.
213 | *
214 | * @returns a function to cancel the listener.
215 | */
216 | export async function attachConsole(): Promise {
217 | return attachLogger(({ level, message }: RecordPayload) => {
218 | switch (level) {
219 | case LogLevel.Trace:
220 | console.log(message);
221 | break;
222 | case LogLevel.Debug:
223 | console.debug(message);
224 | break;
225 | case LogLevel.Info:
226 | console.info(message);
227 | break;
228 | case LogLevel.Warn:
229 | console.warn(message);
230 | break;
231 | case LogLevel.Error:
232 | console.error(message);
233 | break;
234 | default:
235 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
236 | throw new Error(`unknown log level ${level}`);
237 | }
238 | });
239 | }
240 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "tauri-plugin-log-api",
3 | "version": "0.0.0",
4 | "description": "Configurable logging for your Tauri app.",
5 | "license": "MIT or APACHE-2.0",
6 | "authors": [
7 | "Tauri Programme within The Commons Conservancy"
8 | ],
9 | "type": "module",
10 | "browser": "dist-js/index.min.js",
11 | "module": "dist-js/index.mjs",
12 | "types": "dist-js/index.d.ts",
13 | "exports": {
14 | "import": "./dist-js/index.mjs",
15 | "types": "./dist-js/index.d.ts",
16 | "browser": "./dist-js/index.min.js"
17 | },
18 | "scripts": {
19 | "build": "rollup -c"
20 | },
21 | "files": [
22 | "dist-js",
23 | "!dist-js/**/*.map",
24 | "README.md",
25 | "LICENSE"
26 | ],
27 | "devDependencies": {
28 | "tslib": "2.8.1"
29 | },
30 | "dependencies": {
31 | "@tauri-apps/api": "1.6.0"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/rollup.config.mjs:
--------------------------------------------------------------------------------
1 | import { readFileSync } from "fs";
2 |
3 | import { createConfig } from "../../shared/rollup.config.mjs";
4 |
5 | export default createConfig({
6 | input: "guest-js/index.ts",
7 | pkg: JSON.parse(
8 | readFileSync(new URL("./package.json", import.meta.url), "utf8"),
9 | ),
10 | external: [/^@tauri-apps\/api/],
11 | });
12 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Tauri Programme within The Commons Conservancy
2 | // SPDX-License-Identifier: Apache-2.0
3 | // SPDX-License-Identifier: MIT
4 |
5 | use fern::FormatCallback;
6 | use log::{logger, RecordBuilder};
7 | use log::{LevelFilter, Record};
8 | use serde::Serialize;
9 | use serde_repr::{Deserialize_repr, Serialize_repr};
10 | use std::borrow::Cow;
11 | use std::collections::HashMap;
12 | use std::{
13 | fmt::Arguments,
14 | fs::{self, File},
15 | iter::FromIterator,
16 | path::{Path, PathBuf},
17 | };
18 | use tauri::{
19 | plugin::{self, TauriPlugin},
20 | Manager, Runtime,
21 | };
22 |
23 | pub use fern;
24 | use time::OffsetDateTime;
25 |
26 | const DEFAULT_MAX_FILE_SIZE: u128 = 40000;
27 | const DEFAULT_ROTATION_STRATEGY: RotationStrategy = RotationStrategy::KeepOne;
28 | const DEFAULT_TIMEZONE_STRATEGY: TimezoneStrategy = TimezoneStrategy::UseUtc;
29 | const DEFAULT_LOG_TARGETS: [LogTarget; 2] = [LogTarget::Stdout, LogTarget::LogDir];
30 |
31 | /// An enum representing the available verbosity levels of the logger.
32 | ///
33 | /// It is very similar to the [`log::Level`], but serializes to unsigned ints instead of strings.
34 | #[derive(Debug, Clone, Deserialize_repr, Serialize_repr)]
35 | #[repr(u16)]
36 | pub enum LogLevel {
37 | /// The "trace" level.
38 | ///
39 | /// Designates very low priority, often extremely verbose, information.
40 | Trace = 1,
41 | /// The "debug" level.
42 | ///
43 | /// Designates lower priority information.
44 | Debug,
45 | /// The "info" level.
46 | ///
47 | /// Designates useful information.
48 | Info,
49 | /// The "warn" level.
50 | ///
51 | /// Designates hazardous situations.
52 | Warn,
53 | /// The "error" level.
54 | ///
55 | /// Designates very serious errors.
56 | Error,
57 | }
58 |
59 | impl From for log::Level {
60 | fn from(log_level: LogLevel) -> Self {
61 | match log_level {
62 | LogLevel::Trace => log::Level::Trace,
63 | LogLevel::Debug => log::Level::Debug,
64 | LogLevel::Info => log::Level::Info,
65 | LogLevel::Warn => log::Level::Warn,
66 | LogLevel::Error => log::Level::Error,
67 | }
68 | }
69 | }
70 |
71 | impl From for LogLevel {
72 | fn from(log_level: log::Level) -> Self {
73 | match log_level {
74 | log::Level::Trace => LogLevel::Trace,
75 | log::Level::Debug => LogLevel::Debug,
76 | log::Level::Info => LogLevel::Info,
77 | log::Level::Warn => LogLevel::Warn,
78 | log::Level::Error => LogLevel::Error,
79 | }
80 | }
81 | }
82 |
83 | pub enum RotationStrategy {
84 | KeepAll,
85 | KeepOne,
86 | }
87 |
88 | #[derive(Debug, Clone)]
89 | pub enum TimezoneStrategy {
90 | UseUtc,
91 | UseLocal,
92 | }
93 |
94 | impl TimezoneStrategy {
95 | pub fn get_now(&self) -> OffsetDateTime {
96 | match self {
97 | TimezoneStrategy::UseUtc => OffsetDateTime::now_utc(),
98 | TimezoneStrategy::UseLocal => {
99 | OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc())
100 | } // Fallback to UTC since Rust cannot determine local timezone
101 | }
102 | }
103 | }
104 |
105 | #[derive(Debug, Serialize, Clone)]
106 | struct RecordPayload {
107 | message: String,
108 | level: LogLevel,
109 | }
110 |
111 | /// An enum representing the available targets of the logger.
112 | pub enum LogTarget {
113 | /// Print logs to stdout.
114 | Stdout,
115 | /// Print logs to stderr.
116 | Stderr,
117 | /// Write logs to the given directory.
118 | ///
119 | /// The plugin will ensure the directory exists before writing logs.
120 | Folder(PathBuf),
121 | /// Write logs to the OS specific logs directory.
122 | ///
123 | /// ### Platform-specific
124 | ///
125 | /// |Platform | Value | Example |
126 | /// | ------- | --------------------------------------------- | ---------------------------------------------- |
127 | /// | Linux | `{configDir}/{bundleIdentifier}` | `/home/alice/.config/com.tauri.dev` |
128 | /// | macOS | `{homeDir}/Library/Logs/{bundleIdentifier}` | `/Users/Alice/Library/Logs/com.tauri.dev` |
129 | /// | Windows | `{configDir}/{bundleIdentifier}` | `C:\Users\Alice\AppData\Roaming\com.tauri.dev` |
130 | LogDir,
131 | /// Forward logs to the webview (via the `log://log` event).
132 | ///
133 | /// This requires the webview to subscribe to log events, via this plugins `attachConsole` function.
134 | Webview,
135 | }
136 |
137 | #[tauri::command]
138 | fn log(
139 | level: LogLevel,
140 | message: String,
141 | location: Option<&str>,
142 | file: Option<&str>,
143 | line: Option,
144 | key_values: Option>,
145 | ) {
146 | let location = location.unwrap_or("webview");
147 | let mut builder = RecordBuilder::new();
148 | builder
149 | .level(level.into())
150 | .target(location)
151 | .file(file)
152 | .line(line);
153 |
154 | let key_values = key_values.unwrap_or_default();
155 | let mut kv = HashMap::new();
156 | for (k, v) in key_values.iter() {
157 | kv.insert(k.as_str(), v.as_str());
158 | }
159 | builder.key_values(&kv);
160 |
161 | logger().log(&builder.args(format_args!("{message}")).build());
162 | }
163 |
164 | pub struct Builder {
165 | dispatch: fern::Dispatch,
166 | rotation_strategy: RotationStrategy,
167 | timezone_strategy: TimezoneStrategy,
168 | max_file_size: u128,
169 | targets: Vec,
170 | log_name: Option,
171 | }
172 |
173 | impl Default for Builder {
174 | fn default() -> Self {
175 | let format =
176 | time::format_description::parse("[[[year]-[month]-[day]][[[hour]:[minute]:[second]]")
177 | .unwrap();
178 | let dispatch = fern::Dispatch::new().format(move |out, message, record| {
179 | out.finish(format_args!(
180 | "{}[{}][{}] {}",
181 | DEFAULT_TIMEZONE_STRATEGY.get_now().format(&format).unwrap(),
182 | record.level(),
183 | record.target(),
184 | message
185 | ))
186 | });
187 | Self {
188 | dispatch,
189 | rotation_strategy: DEFAULT_ROTATION_STRATEGY,
190 | timezone_strategy: DEFAULT_TIMEZONE_STRATEGY,
191 | max_file_size: DEFAULT_MAX_FILE_SIZE,
192 | targets: DEFAULT_LOG_TARGETS.into(),
193 | log_name: None,
194 | }
195 | }
196 | }
197 |
198 | impl Builder {
199 | pub fn new() -> Self {
200 | Default::default()
201 | }
202 |
203 | pub fn rotation_strategy(mut self, rotation_strategy: RotationStrategy) -> Self {
204 | self.rotation_strategy = rotation_strategy;
205 | self
206 | }
207 |
208 | pub fn timezone_strategy(mut self, timezone_strategy: TimezoneStrategy) -> Self {
209 | self.timezone_strategy = timezone_strategy.clone();
210 |
211 | let format =
212 | time::format_description::parse("[[[year]-[month]-[day]][[[hour]:[minute]:[second]]")
213 | .unwrap();
214 | self.dispatch = fern::Dispatch::new().format(move |out, message, record| {
215 | out.finish(format_args!(
216 | "{}[{}][{}] {}",
217 | timezone_strategy.get_now().format(&format).unwrap(),
218 | record.level(),
219 | record.target(),
220 | message
221 | ))
222 | });
223 | self
224 | }
225 |
226 | pub fn max_file_size(mut self, max_file_size: u128) -> Self {
227 | self.max_file_size = max_file_size;
228 | self
229 | }
230 |
231 | pub fn format(mut self, formatter: F) -> Self
232 | where
233 | F: Fn(FormatCallback, &Arguments, &Record) + Sync + Send + 'static,
234 | {
235 | self.dispatch = self.dispatch.format(formatter);
236 | self
237 | }
238 |
239 | pub fn level(mut self, level_filter: impl Into) -> Self {
240 | self.dispatch = self.dispatch.level(level_filter.into());
241 | self
242 | }
243 |
244 | pub fn level_for(mut self, module: impl Into>, level: LevelFilter) -> Self {
245 | self.dispatch = self.dispatch.level_for(module, level);
246 | self
247 | }
248 |
249 | pub fn filter(mut self, filter: F) -> Self
250 | where
251 | F: Fn(&log::Metadata) -> bool + Send + Sync + 'static,
252 | {
253 | self.dispatch = self.dispatch.filter(filter);
254 | self
255 | }
256 |
257 | pub fn target(mut self, target: LogTarget) -> Self {
258 | self.targets.push(target);
259 | self
260 | }
261 |
262 | pub fn targets(mut self, targets: impl IntoIterator- ) -> Self {
263 | self.targets = Vec::from_iter(targets);
264 | self
265 | }
266 |
267 | /// Writes logs to the given file. Default: .log)
268 | ///
269 | /// Note: This does not modify the directory logs go into. For that refer to `LogTarget::Folder`.
270 | ///
271 | /// # Examples
272 | ///
273 | /// ```
274 | /// use tauri_plugin_log::Builder;
275 | /// let name = "custom-name";
276 | /// let builder = Builder::default()
277 | /// .targets([
278 | /// LogTarget::LogDir
279 | /// ])
280 | /// .log_name(name)
281 | /// .build()
282 | /// ); // Outputs content to custom-name.log
283 | ///
284 | /// ```
285 | pub fn log_name>(mut self, log_name: S) -> Self {
286 | self.log_name = Some(log_name.into());
287 | self
288 | }
289 |
290 | #[cfg(feature = "colored")]
291 | pub fn with_colors(self, colors: fern::colors::ColoredLevelConfig) -> Self {
292 | let format =
293 | time::format_description::parse("[[[year]-[month]-[day]][[[hour]:[minute]:[second]]")
294 | .unwrap();
295 |
296 | let timezone_strategy = self.timezone_strategy.clone();
297 | self.format(move |out, message, record| {
298 | out.finish(format_args!(
299 | "{}[{}][{}] {}",
300 | timezone_strategy.get_now().format(&format).unwrap(),
301 | colors.color(record.level()),
302 | record.target(),
303 | message
304 | ))
305 | })
306 | }
307 |
308 | pub fn build(mut self) -> TauriPlugin {
309 | plugin::Builder::new("log")
310 | .invoke_handler(tauri::generate_handler![log])
311 | .setup(move |app_handle| {
312 | let log_name = self
313 | .log_name
314 | .as_deref()
315 | .unwrap_or_else(|| &app_handle.package_info().name);
316 |
317 | // setup targets
318 | for target in &self.targets {
319 | self.dispatch = self.dispatch.chain(match target {
320 | LogTarget::Stdout => fern::Output::from(std::io::stdout()),
321 | LogTarget::Stderr => fern::Output::from(std::io::stderr()),
322 | LogTarget::Folder(path) => {
323 | if !path.exists() {
324 | fs::create_dir_all(path)?;
325 | }
326 |
327 | fern::log_file(get_log_file_path(
328 | &path,
329 | log_name,
330 | &self.rotation_strategy,
331 | &self.timezone_strategy,
332 | self.max_file_size,
333 | )?)?
334 | .into()
335 | }
336 | LogTarget::LogDir => {
337 | let path = app_handle
338 | .path_resolver()
339 | .app_log_dir()
340 | .ok_or("app_log_dir is None")?;
341 | if !path.exists() {
342 | fs::create_dir_all(&path)?;
343 | }
344 |
345 | fern::log_file(get_log_file_path(
346 | &path,
347 | log_name,
348 | &self.rotation_strategy,
349 | &self.timezone_strategy,
350 | self.max_file_size,
351 | )?)?
352 | .into()
353 | }
354 | LogTarget::Webview => {
355 | let app_handle = app_handle.clone();
356 |
357 | fern::Output::call(move |record| {
358 | let payload = RecordPayload {
359 | message: record.args().to_string(),
360 | level: record.level().into(),
361 | };
362 | let app_handle = app_handle.clone();
363 | tauri::async_runtime::spawn(async move {
364 | let _ = app_handle.emit_all("log://log", payload);
365 | });
366 | })
367 | }
368 | });
369 | }
370 |
371 | self.dispatch.apply()?;
372 |
373 | Ok(())
374 | })
375 | .build()
376 | }
377 | }
378 |
379 | fn get_log_file_path(
380 | dir: &impl AsRef,
381 | log_name: &str,
382 | rotation_strategy: &RotationStrategy,
383 | timezone_strategy: &TimezoneStrategy,
384 | max_file_size: u128,
385 | ) -> plugin::Result {
386 | let path = dir.as_ref().join(format!("{log_name}.log"));
387 |
388 | if path.exists() {
389 | let log_size = File::open(&path)?.metadata()?.len() as u128;
390 | if log_size > max_file_size {
391 | match rotation_strategy {
392 | RotationStrategy::KeepAll => {
393 | let to = dir.as_ref().join(format!(
394 | "{}_{}.log",
395 | log_name,
396 | timezone_strategy
397 | .get_now()
398 | .format(&time::format_description::parse(
399 | "[year]-[month]-[day]_[hour]-[minute]-[second]"
400 | )?)?,
401 | ));
402 | if to.is_file() {
403 | // designated rotated log file name already exists
404 | // highly unlikely but defensively handle anyway by adding .bak to filename
405 | let mut to_bak = to.clone();
406 | to_bak.set_file_name(format!(
407 | "{}.bak",
408 | to_bak
409 | .file_name()
410 | .map(|n| n.to_string_lossy())
411 | .unwrap_or_default()
412 | ));
413 | fs::rename(&to, to_bak)?;
414 | }
415 | fs::rename(&path, to)?;
416 | }
417 | RotationStrategy::KeepOne => {
418 | fs::remove_file(&path)?;
419 | }
420 | }
421 | }
422 | }
423 |
424 | Ok(path)
425 | }
426 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.base.json",
3 | "include": ["guest-js/*.ts"]
4 | }
5 |
--------------------------------------------------------------------------------