1
0
mirror of https://github.com/nicoverbruggen/phpmon.git synced 2025-08-07 20:10:08 +02:00

♻️ Added logger class

This commit is contained in:
2021-12-21 17:06:03 +01:00
parent ceb168c6cf
commit e76c6e14e4
23 changed files with 135 additions and 64 deletions

View File

@ -35,6 +35,9 @@
C40C7F2827721FF600DDDCDC /* ActivePhpInstallation+Checks.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40C7F2727721FF600DDDCDC /* ActivePhpInstallation+Checks.swift */; };
C40C7F2927721FF600DDDCDC /* ActivePhpInstallation+Checks.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40C7F2727721FF600DDDCDC /* ActivePhpInstallation+Checks.swift */; };
C40C7F2B2772201C00DDDCDC /* Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C415D3B62770F294005EF286 /* Actions.swift */; };
C40C7F3027722E8D00DDDCDC /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40C7F2F27722E8D00DDDCDC /* Logger.swift */; };
C40C7F3127722E8D00DDDCDC /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40C7F2F27722E8D00DDDCDC /* Logger.swift */; };
C40C7F3227722E8D00DDDCDC /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40C7F2F27722E8D00DDDCDC /* Logger.swift */; };
C412E5FC25700D5300A1FB67 /* HomebrewPackage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C412E5FB25700D5300A1FB67 /* HomebrewPackage.swift */; };
C415D3B72770F294005EF286 /* Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C415D3B62770F294005EF286 /* Actions.swift */; };
C415D3B82770F294005EF286 /* Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C415D3B62770F294005EF286 /* Actions.swift */; };
@ -189,6 +192,7 @@
C405A4CF24B9B9140062FAFA /* InternetAccessPolicy.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = InternetAccessPolicy.plist; sourceTree = "<group>"; };
C40C7F1D2772136000DDDCDC /* PhpSwitcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhpSwitcher.swift; sourceTree = "<group>"; };
C40C7F2727721FF600DDDCDC /* ActivePhpInstallation+Checks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ActivePhpInstallation+Checks.swift"; sourceTree = "<group>"; };
C40C7F2F27722E8D00DDDCDC /* Logger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = "<group>"; };
C412E5FB25700D5300A1FB67 /* HomebrewPackage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomebrewPackage.swift; sourceTree = "<group>"; };
C415D3B62770F294005EF286 /* Actions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Actions.swift; sourceTree = "<group>"; };
C415D3D62770F341005EF286 /* phpmon-cli */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "phpmon-cli"; sourceTree = BUILT_PRODUCTS_DIR; };
@ -354,6 +358,7 @@
C4B5853D2770FE3900DA4FBE /* Command.swift */,
C4B5853B2770FE3900DA4FBE /* Paths.swift */,
C4B5853C2770FE3900DA4FBE /* Shell.swift */,
C40C7F2F27722E8D00DDDCDC /* Logger.swift */,
);
path = Core;
sourceTree = "<group>";
@ -745,6 +750,7 @@
C40C7F2327721F8200DDDCDC /* ActivePhpInstallation.swift in Sources */,
C4B585462770FE3900DA4FBE /* Command.swift in Sources */,
C40C7F2527721F9800DDDCDC /* HomebrewPackage.swift in Sources */,
C40C7F3227722E8D00DDDCDC /* Logger.swift in Sources */,
C40C7F2B2772201C00DDDCDC /* Actions.swift in Sources */,
C415D3E12770F34D005EF286 /* AllowedArguments.swift in Sources */,
C40C7F202772136000DDDCDC /* PhpSwitcher.swift in Sources */,
@ -786,6 +792,7 @@
C48D0C9325CC804200CC7490 /* XibLoadable.swift in Sources */,
54FCFD2A276C8AA4004CE748 /* CheckboxPreferenceView.swift in Sources */,
C4811D2A22D70F9A00B5F6B3 /* MainMenu.swift in Sources */,
C40C7F3027722E8D00DDDCDC /* Logger.swift in Sources */,
C412E5FC25700D5300A1FB67 /* HomebrewPackage.swift in Sources */,
54AB03262763858F00A29D5F /* Timer.swift in Sources */,
C4C8E81B276F54E5003AC782 /* PhpConfigWatcher.swift in Sources */,
@ -846,6 +853,7 @@
C4F780CD25D80B75000DBC97 /* Alert.swift in Sources */,
C481F79726164A78004FBCFF /* PrefsVC.swift in Sources */,
C41E871B2763D42300161EE0 /* SiteListVC+ContextMenu.swift in Sources */,
C40C7F3127722E8D00DDDCDC /* Logger.swift in Sources */,
C464ADB3275A87CA003FCD53 /* SiteListCell.swift in Sources */,
C415D3E92770F692005EF286 /* AppDelegate+InterApp.swift in Sources */,
C4AF9F78275447F100D44ED0 /* ValetConfigParserTest.swift in Sources */,

View File

@ -15,17 +15,25 @@ import Foundation
// Information about the PHP versions
// etc.: needs to be stored in a separate object we can instantiate here and in PHP Monitor.
print(CommandLine.arguments)
var logger = Log.shared
logger.verbosity = .warning
if CommandLine.arguments.count != 3 {
print("You must enter two arguments.")
if CommandLine.arguments.count < 3 {
Log.err("You must enter at least two additional arguments.")
exit(1)
}
if CommandLine.arguments.contains("-v") || CommandLine.arguments.contains("--verbose") {
logger.verbosity = .info
}
if CommandLine.arguments.contains("-p") || CommandLine.arguments.contains("--performance") {
logger.verbosity = .performance
}
let argument = CommandLine.arguments[1]
if !AllowedArguments.has(argument) {
print("The supported arguments are: \(AllowedArguments.rawValues)")
Log.err("The supported arguments are: \(AllowedArguments.rawValues)")
exit(1)
}
@ -37,9 +45,9 @@ PhpSwitcher.detectPhpVersions()
switch action {
case .use:
let version = CommandLine.arguments[2]
print("Switching to PHP \(version)...")
Log.info("Switching to PHP \(version)...")
break
case .none:
print("Action not recognized!")
Log.err("Action not recognized!")
exit(1)
}

View File

@ -42,8 +42,8 @@ class Actions {
availableVersions: [String],
completed: @escaping () -> Void
) {
print("Switching to \(version) using Valet")
print(valet("use php@\(version)"))
Log.info("Switching to \(version) using Valet")
Log.info(valet("use php@\(version)"))
completed()
}
@ -61,7 +61,7 @@ class Actions {
availableVersions: [String],
completed: @escaping () -> Void
) {
print("Switching to \(version), unlinking all versions...")
Log.info("Switching to \(version), unlinking all versions...")
let group = DispatchGroup()
@ -80,14 +80,14 @@ class Actions {
}
group.notify(queue: .global(qos: .userInitiated)) {
print("All versions have been unlinked!")
print("Linking the new version!")
Log.info("All versions have been unlinked!")
Log.info("Linking the new version!")
let formula = (version == PhpSwitcher.brewPhpVersion) ? "php" : "php@\(version)"
brew("link \(formula) --overwrite --force")
brew("services start \(formula)", sudo: true)
print("The new version has been linked!")
Log.info("The new version has been linked!")
completed()
}
}

View File

@ -0,0 +1,52 @@
//
// Logger.swift
// PHP Monitor
//
// Created by Nico Verbruggen on 21/12/2021.
// Copyright © 2021 Nico Verbruggen. All rights reserved.
//
import Foundation
class Log {
enum Verbosity: Int {
case error = 1,
info = 2,
warning = 3,
performance = 4
public func isApplicable() -> Bool {
return Log.shared.verbosity.rawValue >= self.rawValue
}
}
static var shared = Log()
var verbosity: Verbosity = .info
static func info(_ item: Any) {
if Verbosity.info.isApplicable() {
print(item)
}
}
static func err(_ item: Any) {
if Verbosity.error.isApplicable() {
print(item)
}
}
static func warn(_ item: Any) {
if Verbosity.warning.isApplicable() {
print(item)
}
}
static func perf(_ item: Any) {
if Verbosity.performance.isApplicable() {
print(item)
}
}
}

View File

@ -92,7 +92,7 @@ class PhpExtension {
let file = try? String(contentsOf: path, encoding: .utf8)
if (file == nil) {
print("There was an issue reading the file. Assuming no extensions were found.")
Log.err("There was an issue reading the file. Assuming no extensions were found.")
return []
}

View File

@ -27,7 +27,7 @@ class PhpSwitcher {
from: brewPhpAlias.data(using: .utf8)!
).first!
print("When on your system, the `php` formula means version \(homebrewPackage.version)!")
Log.info("When on your system, the `php` formula means version \(homebrewPackage.version)!")
}
// MARK: - Properties
@ -100,7 +100,7 @@ class PhpSwitcher {
versionsOnly.append(phpAlias)
}
print("The PHP versions that were detected are: \(versionsOnly)")
Log.info("The PHP versions that were detected are: \(versionsOnly)")
availablePhpVersions = versionsOnly

View File

@ -19,7 +19,7 @@ class Utility {
try FileManager.default.copyItem(at: bundleURL, to: targetURL)
return targetURL
} catch let error {
print("Unable to copy file: \(error)")
Log.err("Unable to copy file: \(error)")
}
}

View File

@ -20,13 +20,13 @@ extension App {
func loadGlobalHotkey() {
// Make sure we can retrieve the hotkey from preferences
guard let hotkey = Preferences.preferences[.globalHotkey] as? String else {
print("No global hotkey was saved in preferences. None set.")
Log.info("No global hotkey was saved in preferences. None set.")
return
}
// Make sure we can parse the JSON into the desired format
guard let keybindPref = GlobalKeybindPreference.fromJson(hotkey) else {
print("No global hotkey loaded, could not be parsed!")
Log.err("No global hotkey loaded, could not be parsed!")
shortcutHotkey = nil
return
}

View File

@ -18,11 +18,11 @@ extension AppDelegate {
notificationCenter.delegate = self
notificationCenter.requestAuthorization(options: [.alert], completionHandler: { granted, error in
if !granted {
print("PHP Monitor does not have permission to show notifications.")
Log.warn("PHP Monitor does not have permission to show notifications.")
}
if let error = error {
print("PHP Monitor encounted an error determining notification permissions:")
print(error)
Log.err("PHP Monitor encounted an error determining notification permissions:")
Log.err(error)
}
})
}

View File

@ -51,16 +51,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
*/
var switcher: PhpSwitcher! = nil
var logger: Log = Log.shared
// MARK: - Initializer
/**
When the application initializes, create all singletons.
*/
override init() {
print("==================================")
print("PHP MONITOR by Nico Verbruggen")
print("Version \(App.version)")
print("==================================")
Log.shared.verbosity = .info
Log.info("==================================")
Log.info("PHP MONITOR by Nico Verbruggen")
Log.info("Version \(App.version)")
Log.info("==================================")
self.sharedShell = Shell.user
self.state = App.shared
self.menu = MainMenu.shared

View File

@ -77,7 +77,7 @@ class Startup {
if (!failed) {
initializeSwitcher()
print("PHP Monitor has determined the application has successfully passed all checks.")
Log.info("PHP Monitor has determined the application has successfully passed all checks.")
success()
}
}

View File

@ -25,7 +25,7 @@ class LocalNotification {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
print(error!)
Log.err(error!)
}
}
}

View File

@ -30,7 +30,7 @@ class PMWindowController: NSWindowController, NSWindowDelegate {
}
deinit {
print("Window controller '\(windowName)' was deinitialized")
Log.perf("Window controller '\(windowName)' was deinitialized")
}
}

View File

@ -35,11 +35,11 @@ class HomebrewDiagnostics {
let tapAlias = Shell.pipe("\(Paths.brew) info shivammathur/php/php --json")
if tapAlias.contains("brew tap shivammathur/php") || tapAlias.contains("Error") {
print("The user does not appear to have tapped: shivammathur/php")
Log.info("The user does not appear to have tapped: shivammathur/php")
return false
} else {
print("The user DOES have the following tapped: shivammathur/php")
print("Checking for `php` formula conflicts...")
Log.info("The user DOES have the following tapped: shivammathur/php")
Log.info("Checking for `php` formula conflicts...")
let tapPhp = try! JSONDecoder().decode(
[HomebrewPackage].self,
@ -47,22 +47,22 @@ class HomebrewDiagnostics {
).first!
if tapPhp.version != PhpSwitcher.brewPhpVersion {
print("The `php` formula alias seems to be the different between the tap and core. This could be a problem!")
print("Determining whether both of these versions are installed...")
Log.warn("The `php` formula alias seems to be the different between the tap and core. This could be a problem!")
Log.info("Determining whether both of these versions are installed...")
let bothInstalled = PhpSwitcher.shared.availablePhpVersions.contains(tapPhp.version)
&& PhpSwitcher.shared.availablePhpVersions.contains(PhpSwitcher.brewPhpVersion)
if bothInstalled {
print("Both conflicting aliases seem to be installed, warning the user!")
Log.warn("Both conflicting aliases seem to be installed, warning the user!")
} else {
print("Conflicting aliases are not both installed, seems fine!")
Log.info("Conflicting aliases are not both installed, seems fine!")
}
return bothInstalled
}
print("All seems to be OK. No conflicts, both are PHP \(tapPhp.version).")
Log.info("All seems to be OK. No conflicts, both are PHP \(tapPhp.version).")
return false
}

View File

@ -39,7 +39,7 @@ class Valet {
public func startPreloadingSites() {
if self.sites.count <= 10 {
// Preload the sites and their drivers
print("Fewer than or 11 sites found, preloading list of sites...")
Log.info("Fewer than or 11 sites found, preloading list of sites...")
self.reloadSites()
}
}
@ -50,17 +50,17 @@ class Valet {
public func validateVersion() -> Void {
if version == "UNKNOWN" {
return print("The Valet version could not be extracted... that does not bode well.")
return Log.warn("The Valet version could not be extracted... that does not bode well.")
}
if version.versionCompare(Constants.MinimumRecommendedValetVersion) == .orderedAscending {
let version = version
print("Valet version \(version) is too old! (recommended: \(Constants.MinimumRecommendedValetVersion))")
Log.warn("Valet version \(version) is too old! (recommended: \(Constants.MinimumRecommendedValetVersion))")
DispatchQueue.main.async {
Alert.notify(message: "alert.min_valet_version.title".localized, info: "alert.min_valet_version.info".localized(version, Constants.MinimumRecommendedValetVersion))
}
} else {
print("Valet version \(version) is recent enough, OK (recommended: \(Constants.MinimumRecommendedValetVersion))")
Log.info("Valet version \(version) is recent enough, OK (recommended: \(Constants.MinimumRecommendedValetVersion))")
}
}

View File

@ -55,31 +55,31 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate {
updatePhpVersionInStatusBar()
print("Determining broken PHP-FPM...")
Log.info("Determining broken PHP-FPM...")
// Attempt to find out if PHP-FPM is broken
let installation = PhpSwitcher.phpInstall
installation.notifyAboutBrokenPhpFpm()
// Set up the config watchers on launch (these are automatically updated via delegate methods if the user switches)
print("Setting up watchers...")
Log.info("Setting up watchers...")
App.shared.handlePhpConfigWatcher()
print("Detecting applications...")
Log.info("Detecting applications...")
// Attempt to load list of applications
App.shared.detectedApplications = Application.detectPresetApplications()
let appNames = App.shared.detectedApplications.map { app in
return app.name
}
print("Detected applications: \(appNames)")
Log.info("Detected applications: \(appNames)")
// Load the global hotkey
App.shared.loadGlobalHotkey()
// Attempt to find out more info about Valet
print("PHP Monitor has extracted the version number of Valet: \(Valet.shared.version)")
Log.info("PHP Monitor has extracted the version number of Valet: \(Valet.shared.version)")
Valet.shared.validateVersion()
Valet.shared.startPreloadingSites()
print("PHP Monitor is ready to serve!")
Log.info("PHP Monitor is ready to serve!")
// Schedule a request to fetch the PHP version every 60 seconds
DispatchQueue.main.async { [self] in
@ -232,14 +232,14 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate {
@objc func reloadPhpMonitorMenuInBackground() {
waitAndExecute {
// This automatically reloads the menu
print("Reloading information about the PHP installation (in the background)...")
Log.info("Reloading information about the PHP installation (in the background)...")
}
}
@objc func reloadPhpMonitorMenu() {
waitAndExecute {
// This automatically reloads the menu
print("Reloading information about the PHP installation...")
Log.info("Reloading information about the PHP installation...")
} completion: {
// Add a slight delay to make sure it loads the new menu
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
@ -378,13 +378,13 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate {
DispatchQueue.main.async {
window?.addToConsole(string)
}
print("\(string.trimmingCharacters(in: .newlines))")
Log.perf("\(string.trimmingCharacters(in: .newlines))")
},
didReceiveStdErrData: { string in
DispatchQueue.main.async {
window?.addToConsole(string)
}
print("\(string.trimmingCharacters(in: .newlines))")
Log.perf("\(string.trimmingCharacters(in: .newlines))")
}
)

View File

@ -55,7 +55,7 @@ class Preferences {
if UserDefaults.standard.bool(forKey: PreferenceName.wasLaunchedBefore.rawValue) {
return
}
print("Saving first-time preferences!")
Log.info("Saving first-time preferences!")
UserDefaults.standard.setValue(true, forKey: PreferenceName.wasLaunchedBefore.rawValue)
UserDefaults.standard.synchronize()
}

View File

@ -110,6 +110,6 @@ class PrefsVC: NSViewController {
// MARK: - Deinitialization
deinit {
print("VC deallocated")
Log.perf("PrefsVC deallocated")
}
}

View File

@ -29,7 +29,7 @@ class PrefsWC: PMWindowController {
if let vc = contentViewController as? PrefsVC {
if vc.listeningForHotkeyView != nil {
if event.keyCode == Keys.Escape || event.keyCode == Keys.Space {
print("A blacklisted key was pressed, canceling listen")
Log.info("A blacklisted key was pressed, canceling listen!")
vc.listeningForHotkeyView = nil
} else {
vc.listeningForHotkeyView!.updateShortcut(event)

View File

@ -56,7 +56,7 @@ class ProgressWindowController: NSWindowController, NSWindowDelegate {
}
deinit {
// print("Deinitializing Progress Window Controller")
Log.perf("Deinitializing ProgressWindowController")
}
}
@ -70,7 +70,7 @@ class ProgressViewController: NSViewController {
@IBOutlet weak var imageViewType: NSImageView!
deinit {
// print("Deinitializing Progress View Controller")
Log.perf("Deinitializing ProgressViewController")
}
}

View File

@ -268,6 +268,6 @@ class SiteListVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
// MARK: - Deinitialization
deinit {
print("VC deallocated")
Log.perf("SiteListVC deallocated")
}
}

View File

@ -11,16 +11,16 @@ import Foundation
extension App {
func startWatcher(_ url: URL) {
print("No watcher currently active...")
Log.info("No watcher currently active...")
self.watcher = PhpConfigWatcher(for: url)
self.watcher.didChange = { url in
print("Something has changed in: \(url)")
Log.info("Something has changed in: \(url)")
// Check if the watcher has last updated the menu less than 0.75s ago
let distance = self.watcher.lastUpdate?.distance(to: Date().timeIntervalSince1970)
if distance == nil || distance != nil && distance! > 0.75 {
print("Refreshing menu...")
Log.info("Refreshing menu...")
MainMenu.shared.reloadPhpMonitorMenuInBackground()
self.watcher.lastUpdate = Date().timeIntervalSince1970
}
@ -39,7 +39,7 @@ extension App {
if self.watcher.url != url || forceReload {
self.watcher.disable()
self.watcher = nil
print("Watcher has stopped watching files. Starting new one...")
Log.info("Watcher has stopped watching files. Starting new one...")
startWatcher(url)
}
}

View File

@ -40,8 +40,8 @@ class PhpConfigWatcher {
self.addWatcher(for: self.url.appendingPathComponent("conf.d/\(file)"), eventMask: .write)
}
print("A watcher exists for the following config paths:")
print(self.watchers.map({ watcher in
Log.info("A watcher exists for the following config paths:")
Log.info(self.watchers.map({ watcher in
return watcher.url.relativePath
}))
}
@ -52,14 +52,14 @@ class PhpConfigWatcher {
}
func disable() {
print("Turning off existing watchers...")
Log.info("Turning off existing watchers...")
self.watchers.forEach { (watcher) in
watcher.stopMonitoring()
}
}
deinit {
print("An existing config watcher has been deinitialized.")
Log.perf("A PhpConfigWatcher has been deinitialized.")
}
}