Im using this code to stream into a file. But the created file is empty. Is there something wrong with my code?
const fileStream = pinoms.prettyStream(
{
prettyPrint: {
colorize: true,
levelFirst: true,
translateTime: "yyyy-dd-mm, h:MM:ss TT",
},
},
pinoms.destination({
dest: './my-file', // omit for stdout
minLength: 4096, // Buffer before writing
sync: true}) // Asynchronous logging)
)
const streams = [
{stream: fileStream}
]
const logger = pinoms(pinoms.multistream(streams))
logger.info('HELLO %s!', 'World')
In the documentation it says:
const prettyStream = pinoms.prettyStream(
{
prettyPrint:
{ colorize: true,
translateTime: "SYS:standard",
ignore: "hostname,pid" // add 'time' to remove timestamp
},
prettifier: require('pino-pretty') // not required, just an example of setting prettifier
// as well it is possible to set destination option
}
);
So it should be possible.
PS: I know there is the option to put a writestream with fs into it but I want to get the time formatted.
I found a practicable solution for me. Scince v 7 pino provides the multistream function by it selve. Now I can do all I wanted to do. Using destination and also make the timestamp pretty.
const streams = [
{stream: pino.destination('test.log')},
{stream: pretty({
colorize: true,
sync: true,
})}
]
const logger = pino({level: 'info', timestamp: pino.stdTimeFunctions.isoTime}, pino.multistream(streams))
logger.info('HELLO %s!', 'World')
Related
I'm using the Cypress version 10.3.0 and I'm trying to exclude a specific test file when I do cypress run.
The general purpose of this is due to the fact I want to be able to run all tests when I open CY UI and exclude the all.cy.js from running when I do cypress run to avoid running twice the same tests.
I tried to follow the documentation about excludeSpecPattern which should allow me not to run the test and I implemented this as follow
defineConfig({
e2e: {
chromeWebSecurity: false,
viewportWidth: 1280,
viewportHeight: 800,
screenshotsFolder: 'artifacts',
video: false,
reporter: 'junit',
reporterOptions: {
mochaFile: 'results/test-results-[hash].xml',
},
retries: 1,
defaultCommandTimeout: 60000,
setupNodeEvents(on, config) {
if (config.isTextTerminal) {
// skip the all.cy.js spec in "cypress run" mode
return {
excludeSpecPattern: ['cypress/e2e/all.cy.js'],
}
}
return require('./cypress/plugins/index.js')(on, config);
},
},
I tried to follow a guide here Link to the guide used
However, the above doesn't work as the test immediately fails in 1 sec without even run practically
I don't know how can I do it in my current setup
the plugin called file
const fs = require('fs');
const path = require('path');
const gmail = require('gmail-tester');
function getConfigurationFromFile(file, type) {
const pathToConfigFile = path.resolve('cypress', 'config', type, `${file}.json`);
return JSON.parse(fs.readFileSync(pathToConfigFile));
}
// See https://docs.cypress.io/guides/guides/continuous-integration.html#In-Docker
function disableDevShmUsage(browser = {}, launchOptions) {
if (browser.family === 'chromium' && browser.name !== 'electron') {
launchOptions.args.push('--disable-dev-shm-usage');
}
return launchOptions;
}
/**
* This function is called when a project is opened or re-opened (e.g. due to the project's config changing)
*
* #type {Cypress.PluginConfig}
* #param on - Used to hook into various events Cypress emits (e.g. `on('before:browser:launch', callback)`)
* #param config - The resolved Cypress config
*/
module.exports = (on, config) => {
on('before:browser:launch', disableDevShmUsage);
on('task', {
'gmail:check': async (args) => {
const { from, to, subject } = args;
let fiveMinutesAgo = new Date();
// Will rollover to yy:55 if minutes is xx:00
fiveMinutesAgo.setMinutes(fiveMinutesAgo.getMinutes() - 5);
const email = await gmail.check_inbox(
path.resolve(__dirname, 'credentials.json'), // credentials.json is inside plugins/ directory.
path.resolve(__dirname, 'gmail_token.json'), // gmail_token.json is inside plugins/ directory.
{
subject,
from,
to,
after: fiveMinutesAgo,
include_body: true,
wait_time_sec: 6, // Poll interval (in seconds)
max_wait_time_sec: 60, // Maximum poll interval (in seconds). If reached, return null, indicating the completion of the task().
},
);
return email ?? [];
},
});
const env = config.env.ENVIRONMENT || 'development';
const envConfig = getConfigurationFromFile(env, 'env');
const scope = config.env.SCOPE || 'full';
const scopeConfig = getConfigurationFromFile(scope, 'scope');
return Object.assign(config, envConfig, scopeConfig);
};
I thought maybe I need to include that inside the plugin but still, I have no idea whatever I tried so far with that if statement fails the tests
You would need to merge the result of /cypress/plugins/index.js with your new value.
If not adding the new value, just return the legacyConfig.
defineConfig({
e2e: {
chromeWebSecurity: false,
viewportWidth: 1280,
viewportHeight: 800,
screenshotsFolder: 'artifacts',
video: false,
reporter: 'junit',
reporterOptions: {
mochaFile: 'results/test-results-[hash].xml',
},
retries: 1,
defaultCommandTimeout: 60000,
setupNodeEvents(on, config) {
const legacyConfig = require('./cypress/plugins/index.js')(on, config);
if (config.isTextTerminal) {
// skip the all.cy.js spec in "cypress run" mode
return {
...legacyConfig,
excludeSpecPattern: ['cypress/e2e/all.cy.js'],
}
}
return legacyConfig;
},
},
I have been created my own options and stream for fastify logger:
const logger = pino(
{
level: 'info',
...ecsFormat,
},
pinoMultiStream.multistream([
{ stream: streamToElastic },
{
stream: pretty({
colorize: true,
sync: true,
ignore: 'pid',
}),
},
]),)
const fastify = Fastify({logger})
now I want to extract this options as fastify plugin, how can I do this functionality? If that’s impossible what can I do to extract this code?
You can't encapsulate your code into a Fastify plugin because Fastify's logger has been already created at that time.
In this case, you need to define your own logic to build the fastify server's configuration such as a decorator pattern.
The user experience you will get would be something like:
const decorateLogger = require('my-logger-module')
const applicationConfig = loadAppConfig()
decorateLogger(applicationConfig, options)
const app = Fastify(applicationConfig)
I have the below code
const {
colorize,
combine,
json,
printf,
simple,
timestamp,
errors,
metadata
} = winston.format;
private readonly consoleLogger = new winston.transports.Console({
format: combine(
errors({ stack: true }),
metadata(),
timestamp(),
colorize({ all: true }),
simple(),
printf((info) => {
const { level, message } = info;
if (info?.metadata?.stackTrace) {
return `[${level}] ${message}\r\n${info.metadata.stackTrace}`;
}
return `[${level}] ${message}`;
})
)
});
Based on docs and examples seems colorize will change the color of the whole line.
I was wondering how can I colorize different part of string for example in my code I want timestamp, Level and message have different colors like image below
The possible workaround could be adding colors to custom levels via:
winston.addColors({ yourLevelName: yourColor })
You can see possible color combinations here: https://github.com/winstonjs/winston#using-logging-levels
Then you can address your colors using Colorizer, returned by winston.format.colorize(), and inline them in your printf, for example, the following snippet
import winston from 'winston';
winston.addColors({ request: 'bold cyan magentaBG' });
const colorizer = winston.format.colorize();
const someColoredFormat = format.printf(({ level, timestamp, message, method }) =>
`${timestamp} ${level}: ${colorizer.colorize('request', method)} ${message}`);
const someLogger = createLogger({
level: 'info',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD hh:mm:ss',
}),
format.colorize({
all: true,
}),
someColoredFormat
),
transports: [new transports.Console()],
})
someLogger.info({
method: 'GET',
message: `-- some/api/route`
})
would produce the Output
I think this should help solve your case, however, I can't think of a more idiomatic way to do this, than mixing logging levels
I'm a beginner when it comes to using Uppy. I'm sure that this can be resolved by pros like you. But I am having trouble sending specific meta data information to my upload route.
uppy.js
// Import the plugins
const Uppy = require('#uppy/core');
const XHRUpload = require('#uppy/xhr-upload');
const Dashboard = require('#uppy/dashboard');
const request = require('request');
const uppy = Uppy({
debug: true,
autoProceed: false,
restrictions: {
maxFileSize: 1024000,
maxNumberOfFiles: 3,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', 'video/*']
}
})
.use(Dashboard, {
trigger: '.UppyModalOpenerBtn',
inline: true,
target: '#drag-drop-area',
replaceTargetContent: true,
showProgressDetails: true,
proudlyDisplayPoweredByUppy: false,
animateOpenClose: true,
note: 'Images and video only, 1–3 files, up to 1 MB',
height: 470,
browserBackButtonClose: true,
theme: 'dark',
metaFields: [
{id: 'caption', name: 'Caption', placeholder: 'describe what the image is about'}
]
});
uppy.on('file-added', (file) =>{
console.log(file);
uppy.setFileMeta(file.meta.id, {
caption: file.name
});
});
uppy.use(XHRUpload, {
id: 'XHRUpload',
endpoint: 'http://localhost:8000/upload',
method: 'POST',
formData: true,
fieldName: 'my_file',
metaFields: ['caption'],
bundle: true
});
uppy.on('upload-success', (file, response) => {
//console.log(file.meta.caption);
console.log("File uploaded successfully ", file);
});
module.exports = uppy;
upload.js
router.post('/',(req, res, next) => {
console.log("Coming form uppy.js " , req.body);
});
module.exports = router;
I'm having trouble passing the 'caption' value to my route. When I look on the 'network tab' on Google Chrome's developer tools, it give me a message of 'undefined'. If you can point me at the right direction, I'd appreciate it! Thank you!
First of all need to change file.meta.id to file.id
uppy.on('file-added', (file) =>{
console.log(file);
uppy.setFileMeta(file.id, {
test: 'hello'
});
});
but if you use bundle you should know about that note
Note: When bundle is set to true, only global uppy metadata, the one set via meta options property, is sent to the endpoint. Individual per-file metadata is ignored.
so, if you want send meta data for each file you should change it to false, then you faced with separate request for each file, but all meta data would be present in request
I managed to trigger a job with:
const config = {
languageCode: 'en-US',
enableSpeakerDiarization: true,
audioChannelCount: 2,
enableSeparateRecognitionPerChannel: true,
useEnhanced: true,
profanityFilter: false,
enableAutomaticPunctuation: true,
};
const audio = {
uri: `gs://${filePath}`
}
const requestObj = {
config: config,
audio: audio
}
return speechClient.longRunningRecognize(requestObj)
I get back an object with a name. I want to use that with https://cloud.google.com/speech-to-text/docs/reference/rest/v1/LongRunningRecognizeMetadata (via the node.js package) to get the current status.
How do I do it?
return speechClient.longrunning.Operation()
Seems not to exist
Looks like you can do it with:
return speechClient.operationsClient.getOperation({ name: googleName })
This is not super well documented