Skip to content
Snippets Groups Projects
Commit d707602e authored by Sigmund, Dominik's avatar Sigmund, Dominik
Browse files

Merge branch 'master' into 'main'

Update index.test.js, examples/all-options.js, examples/log-to-file.js,...

See merge request !1
parents e1c10d0e c8964777
No related branches found
No related tags found
1 merge request!1Update index.test.js, examples/all-options.js, examples/log-to-file.js,...
Pipeline #7261 failed
Showing
with 4558 additions and 69 deletions
node_modules
samples/file.log
coverage/
stryker.log
*.DS_Store
image: node:latest
cache:
paths:
- node_modules/
stages:
- test
- publish
test:
stage: test
before_script:
- npm install -g jest
- npm install
script:
- jest
artifacts:
paths:
- docs/test-report.html
- docs/coverage/lcov.info
audit:
stage: test
script:
- npm audit
publish:
only:
refs:
- tags
stage: publish
script:
- npm install --production
- npm publish
.gitlab-ci.yml
\ No newline at end of file
.npmrc 0 → 100755
tag-version-prefix=""
strict-ssl=false
@general:registry=https://gitlab.ard.de/api/v4/projects/930/packages/npm/
//gitlab.ard.de/api/v4/packages/npm/:_authToken=${CI_JOB_TOKEN}
//gitlab.ard.de/api/v4/projects/930/packages/npm/:_authToken=${CI_JOB_TOKEN}
README.md 100644 → 100755
# log # @libs/log
A real simple logger application.
May Optional Log to A File and a loki-server via http or udp.
>__Graylog__ is no longer supported
## Getting started ## Installation
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.ard.de/libs/log.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.ard.de/libs/log/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab. - `npm install --save @libs/log`
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) ## Usage
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
*** `const Log = require('@libs/log')`
`let log = new Log(options)`
# Editing this README Note: The options Part may be omitted, as all parts are optional, but using the name is recommended, as without it, the package-name will be used
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. ### Methods
## Suggestions for a good README - `log.info('This is an Information' )`
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - `log.notice('This is a Notice' )`
- `log.warn('This is a Warning' )`
- `log.error('This is an Error' )`
- `log.fatal('This is a Fatal Message' )`
- `log.debug('This is a Debug Message' )`
## Name You may also add any number of any parameter. The objects will be concatenated using your custom delimeter and stringified.
Choose a self-explaining name for your project.
## Description e.g.:
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges `log.info('this', ['array', 8], 4, {type:'test'})`
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals will logged as (with default format)
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation __YYYY-MM-DDTHH:ii:ss SERVER INFO this ["array",8] 4 {"type": "test"}__
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage ### Formatting
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support You can edit the output using the __format__-Option.
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap Possible Setting:
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing - __{timestamp}__: Display the timestamp in ISO format
State if you are open to contributions and what your requirements are for accepting them. - __{hostname}__: Display the hostname
- __{name}__: Display the Application name
- __{loglevel}__: Display the Loglevel
- __{message}__: Display the Message
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. ### Options
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. >__Graylog__ is no longer supported
## Authors and acknowledgment ```json
Show your appreciation to those who have contributed to the project. {
"name": "Name of App. Default: Name of BaseFolder",
"hostname": "Server Hostname, Default: os.hostname()",
"file": "'File to Append Log to",
"path": "Path Logfile located",
"loglevel": "Minimal LogLevel. Default: WARN",
"delimeter": "How to join multiple outputs. Default: (a single space)",
"format": "Format the output. Default: {timestamp}\\t{hostname}\\t{loglevel}\\t{message}",
"loki": {
"active": "true or false",
"server":"loki-server"
}
}
```
## License ### Examples
For open source projects, say how it is licensed.
## Project status Check the Examples to get a Feeling about the possibilities.
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
const Log = require('../index.js')
let log = new Log({
name: 'Sample-Application',
hostname: 'test-server'
})
log.info('This is an Information')
log.notice('This is a Notice')
log.warn('This is a Warning')
log.error('This is an Error')
log.fatal('This is a Fatal Message')
log.debug('This is a Debug Message')
const Log = require('../index.js')
let log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
loglevel: 'INFO'
})
log.info('This is an Information in default formatting')
log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
loglevel: 'INFO',
format: '{message}'
})
console.log()
console.log('---- Message Only ----')
log.info('Only the message')
log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
loglevel: 'INFO',
format: '{"timestamp":"{timestamp}", "level":"{loglevel}", "message":"{message}"}'
})
console.log()
console.log('---- As JSON ----')
log.info('JSON Output')
var http = require('http');
http.createServer(function (req, res) {
console.log(req.method, req.url)
if (req.method === 'POST' && req.url === '/gelf') {
var body = ''
req.on('data', function(data) {
body += data
})
req.on('end', function() {
console.log(body)
res.writeHead(202, {'Content-Type': 'text/html'})
res.end('post received')
})
}
}).listen(9999)
\ No newline at end of file
var udp = require('dgram')
var server = udp.createSocket('udp4')
// emits when any error occurs
server.on('error',function(error){
console.log('Error: ' + error)
server.close()
})
// emits on new datagram msg
server.on('message',function(msg,info){
console.log('Data received from client : ' + msg.toString())
console.log('Received %d bytes from %s:%d\n',msg.length, info.address, info.port)
})
//emits when socket is ready and listening for datagram msgs
server.on('listening',function(){
var address = server.address()
var port = address.port
var family = address.family
var ipaddr = address.address
console.log('Server is listening at port' + port)
console.log('Server ip :' + ipaddr)
console.log('Server is IP4/IP6 : ' + family)
});
//emits after the socket is closed using socket.close()
server.on('close',function(){
console.log('Socket is closed !')
})
server.bind(9999);
\ No newline at end of file
const Log = require('../index.js')
let log = new Log({
name: 'Sample-File',
file: 'file.log',
path: '/temp'
})
log.info('This is an Information')
log.notice('This is a Notice')
log.warn('This is a Warning')
log.error('This is an Error')
log.fatal('This is a Fatal Message')
log.debug('This is a Debug Message')
const Log = require('../index.js')
let log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
graylog: {
active: true,
mode: 'http',
server: 'http://localhost',
port: 9999
}
})
log.info('This is an Information')
log.notice('This is a Notice')
log.warn('This is a Warning')
log.error('This is an Error')
log.fatal('This is a Fatal Message')
log.debug('This is a Debug Message')
const Log = require('../index.js')
let log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
graylog: {
active: true,
mode: 'udp',
server: 'localhost',
port: 9999
}
})
log.info('This is an Information')
log.notice('This is a Notice')
log.warn('This is a Warning')
log.error('This is an Error')
log.fatal('This is a Fatal Message')
log.debug('This is a Debug Message')
const Log = require('../index.js')
let log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
loki: {
active: true,
server: 'http://localhost:9999'
}
})
log.info('This is an Information')
log.notice('This is a Notice')
log.warn('This is a Warning')
log.error('This is an Error')
log.fatal('This is a Fatal Message')
log.debug('This is a Debug Message')
var http = require('http');
http.createServer(function (req, res) {
console.log(req.method, req.url, req.headers['content-type'])
console.dir(req.headers)
if (req.method === 'POST' && req.url === '/loki/api/v1/push' && req.headers['content-type'] === 'application/json') {
var body = ''
req.on('data', function(data) {
body += data
})
req.on('end', function() {
console.log(body)
res.writeHead(202, {'Content-Type': 'text/html'})
res.end('post received')
})
}
}).listen(9999)
\ No newline at end of file
const Log = require('../index.js')
let log = new Log({
name: 'Sample-Application',
hostname: 'test-server',
loglevel: 'DEBUG'
})
log.info({this: 'is json'})
log.info('This is an Information', 8, ['array', 45, 'mixed', 34.456], {also:'json'})
log.info('test', 'test', 'test')
\ No newline at end of file
const Log = require('../index.js')
let log = new Log()
log.info('This is an Information')
log.notice('This is a Notice')
log.warn('This is a Warning')
log.error('This is an Error')
log.debug('This is a Debug Message')
log.fatal('This is a Fatal Message')
export as namespace Log;
export = Log;
/*~ Write your module's methods and properties in this class */
declare class Log {
constructor(config?: any);
info(...message: any): string;
notice(...message: any): string;
debug(...message: any): string;
warning(...message: any): string;
log(...message: any): string;
}
index.js 0 → 100755
function Log (options) {
this.levels = {
'DEBUG': 5,
'INFO': 4,
'NOTICE': 3,
'WARN': 2,
'ERROR': 1,
'FATAL': 0
}
this.options = options || {}
if (this.options.loglevel) { // DEBUG, INFO, NOTICE, WARN, ERROR, FATAL
this.loglevel = this.levels[this.options.loglevel]
} else {
this.loglevel = 2
}
if (this.options.format) {
this.format = this.options.format
} else {
this.format = '{timestamp}\t{hostname}\t{name}\t{loglevel}\t{message}'
}
if (this.options.delimeter) {
this.delimeter = this.options.delimeter
} else {
this.delimeter = ' '
}
if (this.options.name) {
this.name = this.options.name
} else {
this.name = require('./package.json').name
}
if (this.options.hostname) {
this.hostname = this.options.hostname
} else {
let os = require('os')
this.hostname = os.hostname()
}
if (this.options.loki && this.options.loki.active) {
this.got = require('got')
}
if (this.options.file) {
this.fs = require('fs')
this.path = require('path')
try {
if (!this.fs.existsSync(this.options.path)) {
this.fs.mkdirSync(this.options.path, { recursive: true })
}
} catch (error) {
throw new Error('Could not create path ' + this.options.path + '\n' + error.toString())
}
try {
this.fs.accessSync(this.path.join(this.options.path, this.options.file), this.fs.constants.R_OK | this.fs.constants.W_OK)
} catch (err) {
try {
this.fs.writeFileSync(this.path.join(this.options.path, this.options.file), '', { flag: 'wx' })
} catch (innerErr) {
throw new Error('Could not Create File ' + this.options.file + '\n' + innerErr.toString())
}
}
}
this.info = (...message) => {
if (this.loglevel >= this.levels.INFO) {
return this.log('INFO', ...message)
} else {
return ''
}
}
this.notice = (...message) => {
if (this.loglevel >= this.levels.NOTICE) {
return this.log('NOTICE', ...message)
} else {
return ''
}
}
this.fatal = (...message) => {
if (this.loglevel >= this.levels.FATAL) {
return this.log('FATAL', ...message)
} else {
return ''
}
}
this.warn = (...message) => {
if (this.loglevel >= this.levels.WARN) {
return this.log('WARN', ...message)
} else {
return ''
}
}
this.error = (...message) => {
if (this.loglevel >= this.levels.ERROR) {
return this.log('ERROR', ...message)
} else {
return ''
}
}
this.debug = (...message) => {
if (this.loglevel >= this.levels.DEBUG) {
return this.log('DEBUG', ...message)
} else {
return ''
}
}
this.log = (tag, ...message) => {
let msgString = ''
if (message.length > 1) {
let self = this
msgString = message.reduce( (acc, cur) => {
return acc + self.delimeter + self.objectToString(cur);
})
} else {
msgString = this.objectToString(message[0])
}
let msg = this.format
msg = msg.replace('{timestamp}', this.getDate())
msg = msg.replace('{hostname}', this.hostname)
msg = msg.replace('{name}', this.name)
msg = msg.replace('{loglevel}', tag)
msg = msg.replace('{message}', msgString)
switch (tag) {
case 'INFO':
console.info(msg)
break
case 'NOTICE':
console.log(msg)
break
case 'WARN':
console.warn(msg)
break
case 'ERROR':
console.error(msg)
break
case 'FATAL':
console.error(msg)
break
case 'DEBUG':
console.log(msg)
break
default:
console.log(msg)
}
if (this.options.path && this.options.file) {
this.fs.appendFile(this.path.join(this.options.path, this.options.file), msg + '\n', function (error) {
if (error) {
console.error('Cannot write to File ' + this.options.file)
}
})
}
if (this.options.loki && this.options.loki.active) {
let data = {
streams: [
{
stream: {
hostname: this.hostname,
app: this.name,
level: this.levels[tag]
},
values: [
[(Date.now() * 1000 * 1000).toString(), msg]
]
}
]
}
try {
this.got.post(this.options.loki.server + '/loki/api/v1/push', {body: data, json: true, strictSSL: false})
} catch (error) {
console.error('Could not send to Loki: ' + error.toString())
}
}
return msg
}
this.getDate = () => {
var tzoffset = (new Date()).getTimezoneOffset() * 60000 // offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)
return localISOTime.split('.')[0].trim()
}
this.objectToString = (obj) => {
let add = ''
try {
if (typeof obj === 'string' || obj instanceof String) {
add = obj
} else if(obj instanceof Array) {
add = obj.toString()
} else {
add = JSON.stringify(obj)
}
} catch (error) {
add = obj.toString()
}
return add
}
return this
}
module.exports = Log
/* global it, describe, beforeEach, afterEach */
const os = require('os')
const path = require('path')
const fs = require('fs')
const LOG = require('./index')
const hostname = os.hostname()
function getDate () {
var tzoffset = (new Date()).getTimezoneOffset() * 60000 // offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)
return localISOTime.split('.')[0].trim()
}
const manualhostname = 'testhost'
const name = 'testapp'
let file = 'testfile'
const filePath = '/tmp'
function createLogLine(level, msg) {
return getDate() + '\t' + hostname + '\t@general/log\t' + level + '\t' + msg
}
describe('@general/log', () => {
describe('Contructor', () => {
it('should log default with no options', () => {
let log = new LOG();
expect(log.loglevel).toBe(2)
expect(log.delimeter).toBe(' ')
expect(log.name).toBe('@general/log')
expect(log.hostname).toBe(hostname)
expect(log.format).toBe('{timestamp}\t{hostname}\t{name}\t{loglevel}\t{message}')
})
it('should use option hostname', () => {
let log = new LOG({
hostname: 'test'
});
expect(log.loglevel).toBe(2)
expect(log.delimeter).toBe(' ')
expect(log.name).toBe('@general/log')
expect(log.hostname).toBe('test')
expect(log.format).toBe('{timestamp}\t{hostname}\t{name}\t{loglevel}\t{message}')
})
it('should use option name', () => {
let log = new LOG({
name: 'test'
});
expect(log.loglevel).toBe(2)
expect(log.delimeter).toBe(' ')
expect(log.name).toBe('test')
expect(log.hostname).toBe(hostname)
expect(log.format).toBe('{timestamp}\t{hostname}\t{name}\t{loglevel}\t{message}')
})
it('should use option delimeter', () => {
let log = new LOG({
delimeter: ';'
});
expect(log.loglevel).toBe(2)
expect(log.delimeter).toBe(';')
expect(log.name).toBe('@general/log')
expect(log.hostname).toBe(hostname)
expect(log.format).toBe('{timestamp}\t{hostname}\t{name}\t{loglevel}\t{message}')
})
it('should use option loglevel', () => {
let log = new LOG({
loglevel: 'FATAL'
});
expect(log.loglevel).toBe(0)
expect(log.delimeter).toBe(' ')
expect(log.name).toBe('@general/log')
expect(log.hostname).toBe(hostname)
expect(log.format).toBe('{timestamp}\t{hostname}\t{name}\t{loglevel}\t{message}')
})
it('should use option format', () => {
let log = new LOG({
format: '{message}'
});
expect(log.loglevel).toBe(2)
expect(log.delimeter).toBe(' ')
expect(log.name).toBe('@general/log')
expect(log.hostname).toBe(hostname)
expect(log.format).toBe('{message}')
})
})
describe('log by level', () => {
it('should log fatal only if level is appropriate', () => {
let log = new LOG({loglevel: 'FATAL'});
let logged = log.fatal('test')
expect(logged).toBe(createLogLine('FATAL', 'test'))
log = new LOG({loglevel: 'ERROR'});
logged = log.fatal('test')
expect(logged).toBe(createLogLine('FATAL', 'test'))
log = new LOG({loglevel: 'WARN'});
logged = log.fatal('test')
expect(logged).toBe(createLogLine('FATAL', 'test'))
log = new LOG({loglevel: 'NOTICE'});
logged = log.fatal('test')
expect(logged).toBe(createLogLine('FATAL', 'test'))
log = new LOG({loglevel: 'INFO'});
logged = log.fatal('test')
expect(logged).toBe(createLogLine('FATAL', 'test'))
log = new LOG({loglevel: 'DEBUG'});
logged = log.fatal('test')
expect(logged).toBe(createLogLine('FATAL', 'test'))
})
it('should log error only if level is appropriate', () => {
let log = new LOG({loglevel: 'FATAL'});
let logged = log.error('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'ERROR'});
logged = log.error('test')
expect(logged).toBe(createLogLine('ERROR', 'test'))
log = new LOG({loglevel: 'WARN'});
logged = log.error('test')
expect(logged).toBe(createLogLine('ERROR', 'test'))
log = new LOG({loglevel: 'NOTICE'});
logged = log.error('test')
expect(logged).toBe(createLogLine('ERROR', 'test'))
log = new LOG({loglevel: 'INFO'});
logged = log.error('test')
expect(logged).toBe(createLogLine('ERROR', 'test'))
log = new LOG({loglevel: 'DEBUG'});
logged = log.error('test')
expect(logged).toBe(createLogLine('ERROR', 'test'))
})
it('should log warnings only if level is appropriate', () => {
let log = new LOG({loglevel: 'FATAL'});
let logged = log.warn('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'ERROR'});
logged = log.warn('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'WARN'});
logged = log.warn('test')
expect(logged).toBe(createLogLine('WARN', 'test'))
log = new LOG({loglevel: 'NOTICE'});
logged = log.warn('test')
expect(logged).toBe(createLogLine('WARN', 'test'))
log = new LOG({loglevel: 'INFO'});
logged = log.warn('test')
expect(logged).toBe(createLogLine('WARN', 'test'))
log = new LOG({loglevel: 'DEBUG'});
logged = log.warn('test')
expect(logged).toBe(createLogLine('WARN', 'test'))
})
it('should log notices only if level is appropriate', () => {
let log = new LOG({loglevel: 'FATAL'});
let logged = log.notice('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'ERROR'});
logged = log.notice('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'WARN'});
logged = log.notice('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'NOTICE'});
logged = log.notice('test')
expect(logged).toBe(createLogLine('NOTICE', 'test'))
log = new LOG({loglevel: 'INFO'});
logged = log.notice('test')
expect(logged).toBe(createLogLine('NOTICE', 'test'))
log = new LOG({loglevel: 'DEBUG'});
logged = log.notice('test')
expect(logged).toBe(createLogLine('NOTICE', 'test'))
})
it('should log info only if level is appropriate', () => {
let log = new LOG({loglevel: 'FATAL'});
let logged = log.info('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'ERROR'});
logged = log.info('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'WARN'});
logged = log.info('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'NOTICE'});
logged = log.info('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'INFO'});
logged = log.info('test')
expect(logged).toBe(createLogLine('INFO', 'test'))
log = new LOG({loglevel: 'DEBUG'});
logged = log.info('test')
expect(logged).toBe(createLogLine('INFO', 'test'))
})
it('should log debug only if level is appropriate', () => {
let log = new LOG({loglevel: 'FATAL'});
let logged = log.debug('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'ERROR'});
logged = log.debug('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'WARN'});
logged = log.debug('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'NOTICE'});
logged = log.debug('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'INFO'});
logged = log.debug('test')
expect(logged).toBe('')
log = new LOG({loglevel: 'DEBUG'});
logged = log.debug('test')
expect(logged).toBe(createLogLine('DEBUG', 'test'))
})
})
describe('log messages', () => {
it('should log a string as is', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug('test')
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\ttest'
expect(logged).toBe(expected)
})
it('should log multiple strings with the delimeter', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug('test', 'test', 'test')
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\ttest test test'
expect(logged).toBe(expected)
})
it('should log a number as a string', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug(8)
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\t8'
expect(logged).toBe(expected)
})
it('should log a float as a string', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug(8.23)
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\t8.23'
expect(logged).toBe(expected)
})
it('should log a boolean as a string', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug(true)
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\ttrue'
expect(logged).toBe(expected)
})
it('should log an array as a string', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug(['test', 'test'])
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\ttest,test'
expect(logged).toBe(expected)
})
it('should log a json-object as a string', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug({some: 'value'})
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\t{"some":"value"}'
expect(logged).toBe(expected)
})
it('should log a mixed entry as a string', () => {
let log = new LOG({loglevel: 'DEBUG'});
let logged = log.debug('test', 7, 3.45, false, ['value', 'more'], {some: 'value'})
let expected = getDate() + '\t' + hostname + '\t@general/log\tDEBUG\ttest 7 3.45 false value,more {"some":"value"}'
expect(logged).toBe(expected)
})
})
describe('log formatting', () => {
it('should log message only if set', () => {
let log = new LOG({
format: '{message}',
loglevel: 'DEBUG'
});
let logged = log.debug('test')
let expected = 'test'
expect(logged).toBe(expected)
})
it('should log hostname only if set', () => {
let log = new LOG({
format: '{hostname}',
loglevel: 'DEBUG'
});
let logged = log.debug('test')
let expected = hostname
expect(logged).toBe(expected)
})
it('should log name only if set', () => {
let log = new LOG({
format: '{name}',
loglevel: 'DEBUG'
});
let logged = log.debug('test')
let expected = '@general/log'
expect(logged).toBe(expected)
})
it('should log timestamp only if set', () => {
let log = new LOG({
format: '{timestamp}',
loglevel: 'DEBUG'
});
let logged = log.debug('test')
let expected = getDate()
expect(logged).toBe(expected)
})
it('should log loglevel only if set', () => {
let log = new LOG({
format: '{loglevel}',
loglevel: 'DEBUG'
});
let logged = log.debug('test')
let expected = 'DEBUG'
expect(logged).toBe(expected)
})
it('should log json like message if set', () => {
let log = new LOG({
format: '{"timestamp":"{timestamp}", "level":"{loglevel}", "message":"{message}"}',
loglevel: 'DEBUG'
});
let logged = log.debug('test')
let expected = '{"timestamp":"' + getDate() + '", "level":"DEBUG", "message":"test"}'
expect(logged).toBe(expected)
})
})
describe('log to file', () => {
it('should create the folder if not exists', () => {
let logPath = os.tmpdir() + '/log-test' + Math.floor(Math.random() * 1000)
expect(() => {
fs.accessSync(logPath, fs.constants.R_OK | fs.constants.W_OK)
}).toThrow();
let log = new LOG({
path: logPath,
file: 'test.log'
});
expect(fs.accessSync(logPath, fs.constants.R_OK | fs.constants.W_OK)).toBeUndefined()
})
it('should create the file if not exists', () => {
let logPath = os.tmpdir() + '/log-test' + Math.floor(Math.random() * 1000)
expect(() => {
fs.accessSync(logPath + '/test.log', fs.constants.R_OK | fs.constants.W_OK)
}).toThrow();
let log = new LOG({
path: logPath,
file: 'test.log'
});
expect(fs.accessSync(logPath + '/test.log', fs.constants.R_OK | fs.constants.W_OK)).toBeUndefined()
})
it('should log to a file', (done) => {
let logPath = os.tmpdir() + '/log-test' + Math.floor(Math.random() * 1000)
let log = new LOG({
path: logPath,
file: 'test.log'
});
log.fatal('filetest')
let expected = getDate() + '\t' + hostname + '\t@general/log\tFATAL\tfiletest\n'
setTimeout(()=>{
expect(fs.readFileSync(logPath + '/test.log', 'utf8')).toBe(expected)
done()
},500 )
})
})
// TODO: log to loki
// TODO: add mutation test
})
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment