How to I custom my log format in winston-papertrail? - javascript

I am making an app based on typescript and trying to implement winston-papertrail for logs with a timestamp and custom format. The problem is that when I am consoling it, it is showing exacltly what I want but on papertrail it is showing in an unexpected way. Here is my code on the typescript.
const { Papertrail } = require("winston-papertrail");
const { createLogger, format, transports } = require("winston");
const { combine, timestamp, prettyPrint, printf } = format;
const timezoned = () => {
return new Date().toLocaleString("en-US", {
timeZone: "Asia/Kolkata",
});
};
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const options = {
console: {
level: "debug",
format: combine(
timestamp({format: timezoned}),
myFormat,
) ,
},
};
const winstonPapertrail = new Papertrail({
host: "logs3.papertrailapp.com",
port: 32795,
level: "info",
});
const consoleWinston = new transports.Console(options.console);
export const logger = createLogger({
transports: [winstonPapertrail, consoleWinston],
});
How I am getting it on the console (which is the correct format) :
10/26/2019, 11:15:49 PM info: Fetching offset:16000 count:1000
10/26/2019, 11:15:59 PM info: Products Fetched
10/26/2019, 11:15:59 PM info: Indexing Products
How it is showing on papertrail:
Oct 26 23:15:50 wolborg default info { message: 'Fetching offset:16000 count:1000',
Oct 26 23:15:50 wolborg default info level: 'info',
Oct 26 23:15:50 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:50 wolborg default info [Symbol(message)]:
Oct 26 23:15:50 wolborg default info '{"message":"Fetching offset:16000 count:1000","level":"info"}' }
Oct 26 23:15:59 wolborg default info Products Fetched
Oct 26 23:15:59 wolborg default info { message: 'Products Fetched',
Oct 26 23:15:59 wolborg default info level: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(message)]: '{"message":"Products Fetched","level":"info"}' }
Oct 26 23:15:59 wolborg default info Indexing Products
Oct 26 23:15:59 wolborg default info { message: 'Indexing Products',
Oct 26 23:15:59 wolborg default info level: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(message)]: '{"message":"Indexing Products","level":"info"}' }

Related

React Native:object destructed return undefined

My React Native 0.62.2 destructing a props passed into a class within render () {}:
const {dataLen, img_source, width, ht, index, modalWidth, modalHt} = this.props;
Here is the console output of the props:
[Sat Aug 15 2020 17:42:19.350] LOG props in image disp : {"dataLen": 2, "ht": 352.8, "img_source": "file:///data/user/0/com.xyz_app2/cache/react-native-image-crop-picker/2.jpg", "index": 0, "modalHt": 780.1354401805869, "modalWidth": 360, "sortFn": [Function move], "width": 352.8} //<<== here is the value of props
[Sat Aug 15 2020 17:42:19.366] LOG object
[Sat Aug 15 2020 17:42:19.367] LOG ani code
[Sat Aug 15 2020 17:42:19.455] LOG props in image disp : {"dataLen": 2, "ht": 352.8, "img_source": "file:///data/user/0/com.xyz_app2/cache/react-native-image-crop-picker/7.jpg", "index": 1, "modalHt": 780.1354401805869, "modalWidth": 360, "sortFn": [Function move], "width": 352.8}
[Sat Aug 15 2020 17:42:19.467] LOG object
[Sat Aug 15 2020 17:42:19.484] LOG ani code
[Sat Aug 15 2020 17:42:20.868] LOG [TypeError: undefined is not an object (evaluating '_this.props.img_source')] //<<==here is the error
But there is an error saying that this.props.img_source is undefined when load an component:
<GridImage
img_source={img_source} //<<==this line causes error as img_source undefined
width={width}
ht={ht}
indx={index}
modalWidth={modalWidth}
modalHt={modalHt}
/>
It is a very straight forward object destructing. What is wrong here?

How to implement New FormData() for Array data from Object to do the POST method using Axios, ReactJs?

On the backend I use multer to upload multiple files / images, I have tried using Postman and it works. but when i apply it on the frontend using reactjs, i am confused
sample case:
state = {
name: 'product1',
price: '200',
images: [{name: "1.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
files: [{name: "1.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
}
handleSubmit = () => {
const { name, price, images, files} = this.state
const body = new FormData()
body.append('name', name)
body.append('price', price)
images.map((file, i) => body.append('images[i]', file[i])) // not work
files.map((file, i) => body.append('files[i]', file[i])) // not work
axios.post(`http://localhost:3000/api/v1/add`, body)
.then((res) => res.data.data)
// result {"name":"roduct1","price":"200","images":[{},{}],"files":[{},{}]}
}
You can do the POST request through axios in this way:
var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');
bodyFormData.append('image', imageFile);
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Also its observed many times that localhost does not work with axios. Instead you need to use IP address. If suppose your IP address is 192.23.43.45 than URL becomes http://192.23.43.45:3000/api/v1/add . So, you can try this approach

Cannot get attribute size from File object in React

With input is file, I can log to console the File as
console.log(file.size)
It gives me:
File(3987) {name: "download.jpeg", lastModified: 1544914267262, lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 3987, …}
lastModified: 1544914267262
lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time) {}
name: "download.jpeg"
size: 3987
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
However when I do console.log(e.target.files[0].size)
It does not even fire.
Full Code as requested. FIle is coming from <input onChange={(e)=>{this.handChangeFile(e.target.files[0])}}/>
this.handleChangeFile = (file) => {
console.log(typeof file)
this.setState({ thefile: file })
let fileData = new FileReader();
fileData.readAsDataURL(file);
fileData.onloadend = () => {
imageBase64 = fileData.result
if (this.state.first == true) {
this.setState({ binary: imageBase64, hide_stock: !this.state.hide_stock, first: false }, () => {
})
}
else
this.setState({ binary: imageBase64 }, () => {
})
}
}
This is my solution on jsfiddle
with jQuery: https://jsfiddle.net/huynhsamha/dqLv83zr/
with React: https://jsfiddle.net/huynhsamha/23fv1te5/
Both they are working. Can you share your code why it is not working?
jQuery
<script async src="//jsfiddle.net/huynhsamha/dqLv83zr/embed/js,html,css,result/dark/"></script>
React
<script async src="//jsfiddle.net/huynhsamha/23fv1te5/embed/js,html,css,result/dark/"></script>

Angularjs send empty JSON to server (ONLY in IE 9 and greater)

I have a little issue with my angularjs script.
I'm trying to post data to server (PHP script which saves values to database).
It works correctly in Chrome, Mozilla, Opera and each other but totally not in IE. I tried IE9, 10 and also 11 (all without add-ons)and still can't figure it out.
In IE my angularjs posts only empty JSON (something like {}).
Here's my angularjs POST script.
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'ajax/newInvoice.php',
data : $scope.invoice, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
getInvoices();
$scope.invoice = {items: [{qty: 1,description: '',cost: 0,taxPerc: 21}],odberatel: '',konecny_prijemce: '',datum_objednavky: new Date(),datum_vystaveni: new Date(),datum_splatnosti: new Date(),datum_zdanitelneho_plneni: new Date(),zpusob_uhrady: 'Platba kartou',dodaci_metoda: 'Osobní odběr'};
});
};
And here's PHP.
<?php
require_once '../includes/db.php'; // The mysql database connection script
$created = date("Y-m-d H:i:s", strtotime("now"));
$query = "SELECT id FROM ang_faktury ORDER BY id DESC";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$last_invoice_id = intval($row["id"]);
$year = date("Y");
$month = date("m");
$idString = str_pad(($last_invoice_id + 1), 5, '0', STR_PAD_LEFT);//id faktury ang_faktury[id], ang_faktury_polozky[id_faktury]
$faCislo = 'OB/'.$year.'/'.$month.'/'.$idString; //cislo faktury ang_faktury[cislo_faktury]
$_POST = json_decode(file_get_contents('php://input'), true);
$dzp = $_POST['datum_zdanitelneho_plneni'];
$datum_zdanitelneho_plneni = substr($dzp, 0, 10);
$dzpForm = date("d.m.Y", strtotime($datum_zdanitelneho_plneni));
$do = $_POST['datum_objednavky'];
$datum_objednavky = substr($do, 0, 10);
$doForm = date("d.m.Y", strtotime($datum_objednavky));
$dv = $_POST['datum_vystaveni'];
$datum_vystaveni = substr($dv, 0, 10);
$dvForm = date("d.m.Y", strtotime($datum_vystaveni));
$ds = $_POST['datum_splatnosti'];
$datum_splatnosti = substr($ds, 0, 10);
$dsForm = date("d.m.Y", strtotime($datum_splatnosti));
foreach($_POST['items'] as $item){
$sumPriceTotal += $item['priceTotal'];
$query2="insert into ang_faktury_polozky (id_faktury,name,cena,ks,dph_proc,dph,total) values('$idString','$item[description]','$item[mjPrice]','$item[qty]','$item[taxPerc]','$item[taxSum]','$item[priceTotal]')";
$mysqli->query($query2);
}
$spt = "{$sumPriceTotal}";
$cbd = (($spt*100)/121);
$dph = $spt - $cbd;
$query3="insert into ang_faktury (id,created_at,cislo_faktury,datum_zdanitelneho_plneni,odberatel,konecny_prijemce,zpusob_uhrady,dodaci_metoda,cislo_objednavky,datum_objednavky,datum_vystaveni,datum_splatnosti,cena_bez_dph,dph,celkem_k_uhrade) values('$idString','$created','$faCislo','$dzpForm','$_POST[odberatel]','$_POST[konecny_prijemce]','$_POST[zpusob_uhrady]','$_POST[dodaci_metoda]','$faCislo','$doForm','$dvForm','$dsForm','$cbd','$dph','$spt')";
$mysqli->query($query3);
mysqli_close($mysqli);
?>
Thanks for any advise.
check your data before sending console.log(data),
and check your data after receiving print_r($_POST) (in myFile.php)
from console (newInvoice.php):
Array
(
[items] => Array
(
[0] => Array
(
[qty] => 1
[description] => MIKI_01
[cost] => 10
[taxPerc] => 21
[priceTotal] => 10.00
[taxSum] => 1.74
[mjPrice] => 8.26
)
[1] => Array
(
[qty] => 1
[description] => MIKI_02
[cost] => 20
[taxPerc] => 21
[priceTotal] => 20.00
[taxSum] => 3.47
[mjPrice] => 16.53
)
)
[odberatel] => MIKI
[konecny_prijemce] =>
[datum_objednavky] => 2016-01-16T13:39:32.554Z
[datum_vystaveni] => 2016-01-16T13:39:32.554Z
[datum_splatnosti] => 2016-01-16T13:39:32.554Z
[datum_zdanitelneho_plneni] => 2016-01-16T13:39:32.554Z
[zpusob_uhrady] => Platba kartou
[dodaci_metoda] => Osobní odběr
)
Console (app.js)
Object {items: Array[2], odberatel: "MIKI", konecny_prijemce: "", datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time), datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)…}
datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_splatnosti: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_zdanitelneho_plneni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
dodaci_metoda: "Osobní odběr"
items: Array[2]
0: Object
$$hashKey: "object:4"
cost: 10
description: "MIKI_01"
mjPrice: "8.26"
priceTotal: "10.00"
qty: 1
taxPerc: 21
taxSum: "1.74"
__proto__: Object
1: Object
$$hashKey: "object:69"
cost: 20
description: "MIKI_02"
mjPrice: "16.53"
priceTotal: "20.00"
qty: 1
taxPerc: 21
taxSum: "3.47"
__proto__: Object
length: 2
__proto__: Array[0]
konecny_prijemce: ""
odberatel: "MIKI"
zpusob_uhrady: "Platba kartou"
__proto__: Object

How to process data read from database

I am processing data read from database on the server using the following code:
module.exports = mongoose.model('Todo', {
text : {type : String, default: ''},
created_at : Date
});
var processTodos = function ( todos ){
for (var i = todos.length - 1; i >= 0; i--) {
// Following update is not happening
todos[i].created_at = "Custom date";
};
console.dir(todos);
return todos;
};
I am not able to figure out how to update this. Is there a syntax issue that is causing this.
I am using MEAN stack for my application.
// Following update is not happening
todos[i].created_at = "Custom date";
What am i missing here.
Here is the console log for "console.dir(todos);":
{ _id: 5489dda3f23f159400475dba,
created_at: Thu Dec 11 2014 23:38:35 GMT+0530 (India Standard Time),
__v: 0,
text: 'Testing sorting at server side' }
{ _id: 5489ddacf23f159400475dbb,
created_at: Thu Dec 11 2014 23:38:44 GMT+0530 (India Standard Time),
__v: 0,
text: 'It works' }
{ _id: 5489f31a12fa54cc127f3e1d,
created_at: Fri Dec 12 2014 01:10:10 GMT+0530 (India Standard Time),
__v: 0,
text: 'time to add more data' }
If you'd like to save the changes you're making to your object, you need to persist the change using the .save() method like so:
var processTodos = function ( todos ){
for (var i = todos.length - 1; i >= 0; i--) {
// Following update is not happening
todos[i].created_at = "Custom date";
todos[i].save();
};
console.dir(todos);
return todos;
};

Categories