There are a few third party libraries that are using log4js to output their logs. I know it sounds counter-intuitive but I would like to disable these logs temporarily to be able to investigate an issue that I have.
How do I temporarily disable log4js logs temporarily in code in javascript? Specifically nodejs.
In log4js 5.3.0 (not sure how many versions back it's the same) you can do this by turning everything off temporarily at the root logger, which affects every other logger:
log4js.getLogger().level = 'off';
A full example:
#!/bin/env node
const log4js = require('log4js');
log4js.configure({
appenders: {
out: { type: "stdout" }
},
categories: {
default: {
appenders: [ "out" ],
level: "info"
}
}
});
const rootLogger = log4js.getLogger();
const log = log4js.getLogger('foo');
log.info('this is on - turning off');
rootLogger.level = 'off';
log.info('this is off - turning back on');
rootLogger.level = 'info';
log.info('this is back on');
Which gives you:
[2019-11-13T22:00:37.541] [INFO] foo - this is on - turning off
[2019-11-13T22:00:37.544] [INFO] foo - this is back on
In the app.js file of my nodejs application I place the following code to temporarily disable log4js logs from thirdparty libraries.
const log4js = require('log4js')
log4js.configure({})
This works for disabling the logs.
Related
I am trying to create a deployment or replicaSet with the Kubernetes Javascript client. The Kubernetes javascript client documentation is virtually non-existent.
Is there any way to achieve this?
Assuming that by:
createDeployment()
you are referring to: createNamespacedDeployment()
You can use below code snippet to create a Deployment using Javascript client library:
const k8s = require('#kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.AppsV1Api); // <-- notice the AppsV1Api
// Definition of the deployment
var amazingDeployment = {
metadata: {
name: 'nginx-deployment'
},
spec: {
selector: {
matchLabels: {
app: 'nginx'
}
},
replicas: 3,
template: {
metadata: {
labels: {
app: 'nginx'
}
},
spec: {
containers: [
{
name: 'nginx',
image: 'nginx'
} ]
}
}
}
};
// Sending the request to the API
k8sApi.createNamespacedDeployment('default', amazingDeployment).then(
(response) => {
console.log('Yay! \nYou spawned: ' + amazingDeployment.metadata.name);
},
(err) => {
console.log('Oh no. Something went wrong :(');
// console.log(err) <-- Get the full output!
}
);
Disclaimer!
This code assumes that you have your ~/.kube/config already configured!
Running this code for the first time with:
$ node deploy.js
should output:
Yay!
You spawned: nginx-deployment
You can check if the Deployment exists by:
$ kubectl get deployment nginx-deployment
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-deployment 3/3 3 3 6m57s
Running this code once again will output (deployment already exists!):
Oh no. Something went wrong :(
Additional resources:
Github.com: Kubernetes-client: Javascript
Be careful when you try to deploy a different kinds of resources such as deployment or service.
You need to correctly specify the API version.
const k8sApi = kc.makeApiClient(k8s.AppsV1Api) or (k8s.CoreV1Api) for namespace and etc.
First, you create a kube config object and then create the associated API type. I.e,
import k8s from '#kubernetes/client-node';
const kubeConfig = new k8s.KubeConfig();
kubeConfig.loadFromCluster(); // Or whatever method you choose
const api = kubeConfig.makeApiClient(k8s.CoreV1Api); // Or whatever API
// you'd like to
// use.
const namespace = 'default';
const manifest = new k8s.V1ConfigMap();
// ... additional manifest setup code...
await api.createNamespacedConfigMap(namespace, manifest);
This is the gist of it. If you'd like, I recently created a library with the intention of simplifying interactions with the kubernetes javascript api and it can be found here:
https://github.com/ThinkDeepTech/k8s
If it doesn't help you directly, perhaps it can serve as an example of how to interact with the API. I hope that helps!
Also, make sure the application executing this code has the necessary permissions (i.e, the K8s Role, RoleBinding and ServiceAccount configs) necessary to perform the actions you're attempting. Otherwise, it'll error out.
I am using ElectronJS in order to build a Desktop Application.
However, I would like to auto-update the changes in the code and see the result immediately.
For example, if I am creating a WebServer with express on localhost, alyways when i update the browser, i get the changes.
On the Go Live extension on VSCode, this happens automatically after CRTL + Save
Does there exist any similar functionality for electron?
My current alternative is to close the whole electron application and start it with npm start again...
Thanks.
use electron-hot-reload package get hotreload
import { mainReloader, rendererReloader } from 'electron-hot-reload';
import { app } from 'electron';
import path from 'path';
const mainFile = path.join(app.getAppPath(), 'dist', 'main.js');
const rendererFile = path.join(app.getAppPath(), 'dist', 'renderer.js');
mainReloader(mainFile, undefined, (error, path) => {
console.log("It is a main's process hook!");
});
rendererReloader(rendererFile, undefined, (error, path) => {
console.log("It is a renderer's process hook!");
});
Example project with configuration
https://github.com/valentineus/electron-hot-reload/tree/6feca4b65b78c674aea096906ecd7b46abebc36a/example/application/src
Found it on my own.
As #ShioT mentioned, this is called hot reload / live reload.
electron-reload | npm package
https://www.npmjs.com/package/electron-reload
Frontend
require('electron-reload')(__dirname);
Backend (hard reset)
const path = require('path')
require('electron-reload')(__dirname, {
// note that this path can vary
electron: path.join(__dirname, 'node_modules', '.bin', 'electron')
});
The simplest way I've found is using electron-reloader, after installation, just paste the following code at the top of the app entry file, and you're all set:
const { app } = require('electron')
app.isPackaged || require('electron-reloader')(module)
I am trying to get the package electron-dl working. For that, i use the standard electron-quick-start example project.
Unfortunately, applying the example code from electron-dl to the electon-quick-start example does not work for me, meaning nothing is happening and no errors in the browser-console or the terminal.
This is how i implemented the minimal example:
main.js
const {app, BrowserWindow, ipcMain} = require('electron')
const {download} = require('electron-dl');
let mainWindow
ipcMain.on('download-item', async (event, {url}) => {
event.sender.send('download-success', url)
console.log(url)
const win = BrowserWindow.getFocusedWindow();
console.log(await download(win, url));
});
// ...
renderer.js
const { ipcRenderer } = require('electron')
$('#btn-dl').click(() => {
const newURL = "http://ipv4.download.thinkbroadband.com/5MB.zip"
ipcRenderer.send('download-item', {url: newURL})
})
ipcRenderer.on('download-success', (event, arg) => {
console.log(arg)
})
index.html
<h1>Hello World!</h1>
<button id="btn-dl">Download</button>
<script>
// jQuery
$ = require('jquery')
// You can also require other files to run in this process
require('./renderer.js')
</script>
In this implementation i am simply trying to download the file 5MB.zip when pressing the Download button.
What am i doing wrong?
Could someone please provide a simple working example of the implenentation of electron-dl using the electron-quick-start example?
Thanks for your help!
Having recreated exactly what you described, it works flawlessly for me.
The following is output on the console:
http://ipv4.download.thinkbroadband.com/5MB.zip
DownloadItem {
_events: { updated: [Function], done: [Function] },
_eventsCount: 2 }
The package determines the location to store the file itself, if you don't specify it. You can output the path it chooses by default using app.getPath('downloads'). For me, this is my home directory (Linux).
If you want to set the download directory yourself:
download(win, url, {
directory: "/path/to/my/directory/"
})
The package will create directories as needed.
I would just like to add, I had spent a couple of days messing around with this issue. I encountered the exact same thing on my project. By disabling my antivirus shields, it stopped interrupting the downloads. Make sure you make an exception for your project / any visual studio code processes. I just chose to disable the shield as a whole.
Edit: do so at your own risk.
My log4js.js file code
'use strict';
var log4js = require('log4js');
var log4jsGen = {
getLogger: function getLogger() {
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('./ApplicationLogs.log'), 'logs');
var logger = log4js.getLogger('logs');
return logger;
}
};
module.exports = log4jsGen;
My conf.js file(specific to appender section only)
"appenders": [{
"type": "log4js-protractor-appender",
"append": 'false',
"maxLogSize": 20480,
"backups": 3,
"category": "relative-logger"
}],
Problem:
1) IS there a way that the logs will get overwritten in each run.
2) Why log4js-protractor-appender is not working, instead log4js is working, the merit of the previous is that it resolves the promises which is passed as an argument.
Thats a great question. Yes log4js-protractor-appender is awesome. It is built specially for Protractor based environments and it places all logger command in Protractor Control flow and resolves Protractor promises before logging.
You were using it incorrectly. The appender options are not part of Protractor config options but can be integrated. The approach you have is a little old one and I have updated by blog post
These are the steps as an answer to your question-2
Step 1: Install log4js npm module
Step 2: Install log4js-protractor-appender module
Step 3: Add the logger object creation logic in protractor beforeLaunch() and assign it onto browser protractor global object
'use strict';
var log4js = require('log4js');
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: [
{ type: 'log4js-protractor-appender', category: 'protractorLog4js' },
{
type: "file",
filename: './logs/ExecutionLog.log',
category: 'protractorLog4js'
}
]
});
},
onPrepare: function() {
browser.logger = log4js.getLogger('protractorLog4js');
},
Step 4: Use logger object in your tests by accessing through browser.logger
describe('sample test', function(){
it('Sample Check', function(){
browser.get("http://www.protractortest.org/#/");
browser.logger.info("Testing Log4js");
browser.sleep(5000);
browser.logger.info('Displayed text is:', browser.getCurrentUrl());
var elm = element(by.css('.lead'))
browser.logger.info('Displayed text is:', elm.getText());
});
});
But one thing to note is - This appender is just an console appender and will not be able to write to file. The file will still contain unresolved promises
Sample Output:
[21:54:23] I/local - Starting selenium standalone server...
[21:54:23] I/launcher - Running 1 instances of WebDriver
[21:54:25] I/local - Selenium standalone server started at http://192.168.1.5:60454/wd/hub
Started
[2017-02-03 21:54:30.905] [INFO] protractorLog4js - Testing Log4js
[2017-02-03 21:54:35.991] [INFO] protractorLog4js - Displayed text is: http://www.protractortest.org/#/
[2017-02-03 21:54:36.143] [INFO] protractorLog4js - Displayed text is: Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.
.
Answer to your Question 1: How to overwrite logs each run. I added a simple logic in beforeLaunch() to delete old logs if they exist and its part of the code snippet I pasted above
I have check this issue with and followed the steps mentioned in Answer 1 and it works for me.
Earlier I was getting log output in Console only but now I am getting log in console and file also.
I corrected the file path passing and Set type: "file" in log4js configure in conf file.
Log4js in Conf file
Log appender in file
Please let me know if you face any issue again.
Thanks
I've created Node js with express and currently I use the console.log to log message and morgan for expresss...for production use what is recommended approach to use for error handling and logging ,there is recommended modules to use?
Examples will be very useful!
I try with the following
module.exports = function () {
var logger = new winston.Logger({
levels: {
info: 1
},
transports: [
new (winston.transports.File)({
level: 'info',
filename: path.join(process.cwd(), '/logs/log.json'),
})
]
});
}
I have used winston in the past quite effectively. In the below excerpt we are creating a custom log level called info such that we can call logger.info to log messages. I believe there are numerous default levels defined on winston which are well documented.
The second part is to define a transport. In winston this is essentially a storage device for your logs. You can define multiple transports in the array including Console logging, File logging, Rotated file logging, etc... These are all well documented here. Im my example I have created a file transport where the log file is located under log/logs.json within the root of the application. Every time I now call logger.info('blah blah blah') I will see a new log entry in the file.
var winston = require('winston'),
, path = require('path')
// Log to file.
var logger = new winston.Logger({
levels: {
info: 1
},
transports: [
new (winston.transports.File)({
level: 'info',
filename: path.join(process.cwd(), '/log/logs.json'),
})
]
});
// Write to log.
logger.info("something to log");